Spring服务定制及相关问题解决


问题总述

​我们都知道如果使用Spring来进行bean管理的时候。如果同一个接口的实现类存在两个,直接使用@Autowired注解来实现bean注入,会在启动的时候报异常。我们通常的做法是使用@Resource注解来执行bean的名称。不过通过@Resource注解类似于硬编码的方式,如果我们想修改接口的具体实现,必须修改代码。假设我们环境中针对所有接口,都有两套实现,一套在测试环境中使用,一个在生产环境中使用。那么当切换环境的时候,所有接口使用@Resource注入的地方都需要修改bean名称。

使用@Profile注解

​ 针对前面两套环境的情况,我们可以使用@Profile注解来轻松解决。具体代码示例如下:

public interface HelloService {
    
    void saySomething(String msg);
}

@Profile("kind1")
@Service
public class HelloServiceImpl1 implements HelloService {
    public void saySomething(String msg) {
        System.out.println("HelloServiceImpl1 say:" + msg);
    }
}

@Profile("kind2")
@Service
public class HelloServiceImpl2 implements HelloService {
    public void saySomething(String msg) {
        System.out.println("HelloServiceImpl2 say:" + msg);
    }
}

@EnableAspectJAutoProxy
@Configurable
@ComponentScan(basePackages="com.rampage.spring")
@EnableScheduling
public class ApplicationConfig {
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=ApplicationConfig.class)
@ActiveProfiles(profiles={"kind1"})     // 启用kind1注入的bean
public class HelloServiceTest {
    
    @Autowired
    private HelloService helloService;
    
    @Test
    public void testServiceSelector() {
        helloService.saySomething("I Love U!");
    }
}

​ 最终输出的结果为:

HelloServiceImpl1 say:I Love U!

多服务共存定制

​ 考虑这样一种情况,假设HelloService是针对全国通用的服务,对于不同的省市使用不同的方言来saySomething

相关内容

    暂无相关文章