为了实现一个接口多个实现类自由切换,我们将使用注入跟配置文件的方式实现该功能,以致于减少硬编码的校验,降低组件间的耦合性。
假设我们定义了如下接口跟实现类:
public interface ITestService {
void test();
}
@Service("s1")
public class TestServiceImpl1 implements ITestService {
@Override
public void test() {
System.out.println("接口1实现类 ...");
}
}
@Service("s2")
public class TestServiceImpl2 implements ITestService {
@Override
public void test() {
System.out.println("接口2实现类 ...");
}
}
那么我们如何通过注入的方式使用这个接口呢?
关于java的多种注入方式:
1.通过 @Autowired+@Qualifier(name=“spring管理的实现类名称”)配合注入
@Autowired
@Qualifier("TestServiceImpl1")
ITestService testService; //正常启动
2.通过@Resource注入,根据默认类名区分
@Resource(name = "TestServiceImpl1")
ITestService testService; //正常启动
3.通过@Resource注入,根据@Service指定的名称区分
@Resource(name = "s1")
ITestService testService; //正常启动
有了接口注入方式,那么我们如何实现可控注入呢?
使用配置文件控制注入:
我们需要在实现类上添加配置文件注解,使用配置文件控制该实现类是否生效
@Service
@Configuration
@ConditionalOnProperty(prefix = "demo.test.service", name = "impl", havingValue = "one")
public class TestService1 implements ITestService {
@Override
public void test() {
System.out.println("接口1实现类 ...");
}
}
@Service
@Configuration
@ConditionalOnProperty(prefix = "demo.test.service", name = "impl", havingValue = "two")
public class TestService2 implements ITestService {
@Override
public void test() {
System.out.println("接口2实现类 ...");
}
}
application.properties 配置文件:
demo.test.service.impl=one
使用接口:
@Autowired
ITestService service;
public void run() {
service.test();
}
参考资料:
spring一个接口多个实现类的注入 和 使用配置文件控制的场
————————————————
版权声明:本文为CSDN博主「Easion.Y」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq506930427/article/details/107762204