如何解决使用Spring根据配置参数注入正确的实现
我正在使用Springboot,因此使用了Spring依赖注入框架。我想知道是否可以根据配置参数的值注入接口的特定实现
假设我有一个接口MyInterface
和两个实现MyImplementation1
和MyImplementation2
interface MyInterface {
...
}
@Component
public class MyImplementation1 implements MyInterface {
...
}
@Component
public class MyImplementation2 implements MyInterface {
...
}
我有一个配置类MyConfiguration
@Component
@ConfigurationProperties("my.configuration")
public class MyConfiguration {
protected boolean myBoolean;
...
}
现在,我想将MyImplementation1
注入MyClass
类,如果myBoolean == true
注入MyImplementation2
myBoolean == false
我应该怎么办?
感谢帮助
解决方法
当某些属性设置为期望值时,可以使用@ConditionalOnProperty
创建一个bean。
interface MyInterface {
...
}
@Component
@ConditionalOnProperty(value="my.configuration.my-boolean",havingValue = "true",matchIfMissing = true)
public class MyImplementation1 implements MyInterface {
...
}
@Component
@ConditionalOnProperty(value="my.configuration.my-boolean",havingValue = "false")
public class MyImplementation2 implements MyInterface {
...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。