Spring boot 根据Spring Boot上的属性实例化服务
一个好的实践是将服务定义为接口及其在类上的实现 假设我有两个实现相同接口的类,我想根据属性(而不是概要文件)来区分它们。我的意思是,如果我有Spring boot 根据Spring Boot上的属性实例化服务,spring-boot,dependency-injection,autowired,Spring Boot,Dependency Injection,Autowired,一个好的实践是将服务定义为接口及其在类上的实现 假设我有两个实现相同接口的类,我想根据属性(而不是概要文件)来区分它们。我的意思是,如果我有@Autowire-private-myService-interface-myService如果我有myproperty=potato我想接收一个PotatoServiceImpl的实例,或者如果我有myproperty=potato我想接收一个TomatoServiceImpl的实例 我没有使用个人资料 注:当我说属性时,我指的是应用程序中的属性。属性看
@Autowire-private-myService-interface-myService
如果我有myproperty=potato
我想接收一个PotatoServiceImpl
的实例,或者如果我有myproperty=potato
我想接收一个TomatoServiceImpl
的实例
我没有使用个人资料
注:当我说属性时,我指的是应用程序中的属性。属性看:
public interface MyInterface {
}
@Component
@ConditionalOnProperty(prefix = "myproperty" havingValue = "potato", matchIfMissing = false)
public class MyPotatoImpl implements MyInterface {
}
@Component
@ConditionalOnProperty(prefix = "myproperty" havingValue = "tomato", matchIfMissing = false)
public class MyTomatoImpl implements Myinterface {
}
@Component
public class Consumer {
@Autowire
private MyInterface tomatoOrPotato; //depending on property myproperty value
}
对于我来说,这是一个非常优雅的解决方案,可以实现spring风格的策略创意设计模式。
查找有关@ConditionalOnProperty
注释的文档。查找:
public interface MyInterface {
}
@Component
@ConditionalOnProperty(prefix = "myproperty" havingValue = "potato", matchIfMissing = false)
public class MyPotatoImpl implements MyInterface {
}
@Component
@ConditionalOnProperty(prefix = "myproperty" havingValue = "tomato", matchIfMissing = false)
public class MyTomatoImpl implements Myinterface {
}
@Component
public class Consumer {
@Autowire
private MyInterface tomatoOrPotato; //depending on property myproperty value
}
对于我来说,这是一个非常优雅的解决方案,可以实现spring风格的策略创意设计模式。
查找有关@ConditionalOnProperty
注释的文档。我工作过,我只想指出,与其使用前缀,不如使用名称。是的,你是对的。当您有一个由多个点分隔的部分组成的属性时,例如mySection.coolProperty
,您可以将前缀
属性指定为mySection
,将名称
指定为coolProperty
,我只是想说,与其使用前缀
,不如使用名称
。是的,你是对的。当您有一个由多个点分隔的部分组成的属性时,例如mySection.coolProperty
,您可以将前缀
属性指定为mySection
,将名称
指定为coolProperty
。