使用Springboot2和java8。
我有一个@Configuration类,它将根据某些属性实例化一个bean,根据这些属性,实例化的bean应该是主类还是非主类。
@Configuration
public class MyConfClass {
@Autowired
private MyProperties myProperties;
@Bean
@ConditionalOnProperty(name = "property.use-default", havingValue = "false", matchIfMissing = true)
public MySpringBean buildMySpringBean() {
MySpringBean bean = new MySpringBean();
if (myProperties.isPrimary()) {
// Should be primary like if annotated with @Primary
} else {
// should not
}
return bean;
}
}
发布于 2020-02-27 18:26:18
通常,您可以尝试创建自己的BeanFactoryPostProcessor
,将Primary
参数设置为基于配置的bean定义,但这意味着您将深入研究spring的内部结构。
如果你不想摆弄这个相当先进的概念,
也许你可以采用以下方法:
@Configuration
public class MyConfClass {
@Bean
@Primary
@ConditionalOnProperty(name = "shouldBeDefault", havingValue = "true", matchIfMissing = true)
public MySpringBean buildMySpringBeanPrimary() {
return new MySpringBean();
}
@Bean
@ConditionalOnProperty(name = "shouldBeDefault", havingValue = "false", matchIfMissing = false)
public MySpringBean buildMySpringBeanNotPrimary() {
return new MySpringBean();
}
坦率地说,我不明白什么是property.use-default
属性,但如果你也必须依赖于这个条件,那么你可能不得不准备“复合条件”,只有当两个“底层”条件都为真时,它才会计算为“真”。
这很容易做到,正如Here所解释的那样。
更新
由于这里看起来您将使用BeanFactoryPostProcessor
,下面是应该可以使用的示例(可能需要做一些小改动):
@Component // or register it in @Configuration as if its a regular bean
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
private final Environment env;
public MyBeanFactoryPostProcessor(Envrionment env) {this.env = env;}
public void postProcessBeanFactory(ConfiguratbleListableBeanFactory beanFactory) throws BeansException {
boolean shouldBePrimary = resolveShouldBePrimary();
if(shouldBePrimary) {
BeanDefinition bd = beanFactory.getBeanDefinition("yourBeanName");
bd.setPrimary(true);
}
}
private boolean resolveShouldBePrimary() {
// here you can read properies directly or if you work with @ConfigurationProperties annotated class you can do:
MyConfigProperties myConfigProperties = Binder.get(env).bind("prefix.in.config", MyConfigProperties.class).get()
// now resolve from the mapped class
}
}
https://stackoverflow.com/questions/60430847
复制相似问题