【问题标题】:Spring: Using @Configuration to dynamically return a Bean [closed]Spring:使用@Configuration 动态返回一个Bean [关闭]
【发布时间】:2013-04-12 18:08:30
【问题描述】:

假设您需要动态(在运行时)获取给定类型的子类型的实例。

您将如何使用 Spring IoC 实现这一目标?

【问题讨论】:

  • 您可以通过使用配置文件以更具声明性的方式实现同​​样的目的
  • 你还没有问过问题。
  • @SotiriosDelimanolis 我要发布一个问题,但是当我遇到解决方案时,我决定将其公开,然后认为“回答你自己的问题”选项是解决问题的方法。 blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/ “如果您有一个问题,如果您想记录在公开,以便其他人(包括您自己)以后可以找到它可以在相关的 Stack Exchange 站点上提出并回答您自己的问题。(...)不仅可以提出和回答您自己的问题,还可以明确鼓励”
  • @DiegoAlcántara 您可以将答案添加为答案,它会更明显。
  • @NilsH 您能否扩展您的评论作为答案?

标签: java spring spring-ioc


【解决方案1】:

您还可以使用@Profile 以更具声明性的方式实现类似的功能。

@Configuration
@Profile("default")
public class TypeAConfig {
    @Bean
    public Type getType() {
        return new TypeA();
    }
}

@Configuration
@Profile("otherProfile")
public class TypeBConfig() {
    @Bean
    public Type getType() {
        return new TypeB();
    }
}

@Configuration
public class SysConfig {
    @Autowired
    Type type;       

    @Bean Type getType() {
        return type;
    }
}

然后您可以通过指定 Spring 应该激活的配置文件来控制要使用的实现,例如使用spring.profiles.active 系统属性。更多信息在JavaDoc for Profile

【讨论】:

    【解决方案2】:

    我发现以下是一种简单的方法。

    @Component
    public class SystemPreferences {
      public boolean useA() {...}
    }
    
    interface Type {....}
    
    public class TypeA implements Type {
       @Autowired
       Other xyz;
    }
    
    public class TypeB implements Type {...}
    
    @Configuration
    public class SysConfig {
      @Autowired
      SystemPreferences sysPrefs;
    
      @Bean
      public Type getType() {
        if (sysPrefs.useA()) {
          //Even though we are using *new*, Spring will autowire A's xyz instance variable
          return new TypeA();
        } else {
          return new TypeB();
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-15
      • 2014-03-27
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多