Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring boot 根据Spring Boot上的属性实例化服务_Spring Boot_Dependency Injection_Autowired - Fatal编程技术网

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