首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Spring,是否可以在@Bean方法中决定使用@Primary

Spring,是否可以在@Bean方法中决定使用@Primary
EN

Stack Overflow用户
提问于 2020-02-27 18:16:07
回答 1查看 270关注 0票数 0

使用Springboot2和java8。

我有一个@Configuration类,它将根据某些属性实例化一个bean,根据这些属性,实例化的bean应该是主类还是非主类。

代码语言:javascript
运行
复制
@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;
    }
}
EN

回答 1

Stack Overflow用户

发布于 2020-02-27 18:26:18

通常,您可以尝试创建自己的BeanFactoryPostProcessor,将Primary参数设置为基于配置的bean定义,但这意味着您将深入研究spring的内部结构。

如果你不想摆弄这个相当先进的概念,

也许你可以采用以下方法:

代码语言:javascript
运行
复制
@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,下面是应该可以使用的示例(可能需要做一些小改动):

代码语言:javascript
运行
复制
@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     
   }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60430847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档