创建 bean 取决于 spring 配置文件
Create beans depends on spring profile
我有一个奇怪的问题。
创建 bean 取决于 spring 配置文件。创建注释并在 bean class 上使用它。
注释:
@Profile("dev")
public @interface Dev {
}
@Profile("prod")
public @interface Prod {
}
使用:
public interface Facade {
String test();
}
@Dev
@Component("facade")
public class DevFacade implements Facade {
public String test() {
return "Dev";
}
}
@Prod
@Component("facade")
public class ProdFacade implements Facade{
public String test() {
return "Prod";
}
}
直到 spring 引导版本 2.1。18.RELEASE 它工作正常。当我设置 spring.profiles.active=dev
时,我只会得到 bean DevFacade
。但是高于版本 2.2.0.RELEASE 它不起作用,我明白了
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'facade' for bean class [com.example.demo.test.ProdFacade] conflicts with existing, non-compatible bean definition of same name and class [com.example.demo.test.DevFacade]
。这意味着 Spring 为 dev 和 prod 配置文件创建 beans,但为什么呢?
当我修改 classes 并使用 @Profile("dev")
而不是 @Dev
时,它起作用了。
有人知道为什么吗?
用户留存注释。 @保留(RetentionPolicy.RUNTIME)
@Retention(RetentionPolicy.RUNTIME)
@Profile("dev")
public @interface Dev {
}
@Retention(RetentionPolicy.RUNTIME)
@Profile("prod")
public @interface Prod {
}
我有一个奇怪的问题。 创建 bean 取决于 spring 配置文件。创建注释并在 bean class 上使用它。 注释:
@Profile("dev")
public @interface Dev {
}
@Profile("prod")
public @interface Prod {
}
使用:
public interface Facade {
String test();
}
@Dev
@Component("facade")
public class DevFacade implements Facade {
public String test() {
return "Dev";
}
}
@Prod
@Component("facade")
public class ProdFacade implements Facade{
public String test() {
return "Prod";
}
}
直到 spring 引导版本 2.1。18.RELEASE 它工作正常。当我设置 spring.profiles.active=dev
时,我只会得到 bean DevFacade
。但是高于版本 2.2.0.RELEASE 它不起作用,我明白了
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'facade' for bean class [com.example.demo.test.ProdFacade] conflicts with existing, non-compatible bean definition of same name and class [com.example.demo.test.DevFacade]
。这意味着 Spring 为 dev 和 prod 配置文件创建 beans,但为什么呢?
当我修改 classes 并使用 @Profile("dev")
而不是 @Dev
时,它起作用了。
有人知道为什么吗?
用户留存注释。 @保留(RetentionPolicy.RUNTIME)
@Retention(RetentionPolicy.RUNTIME)
@Profile("dev")
public @interface Dev {
}
@Retention(RetentionPolicy.RUNTIME)
@Profile("prod")
public @interface Prod {
}