【问题标题】:autowire a Spring bean based on the value of a property根据属性的值自动装配 Spring bean
【发布时间】:2014-11-05 21:14:15
【问题描述】:

n我正在使用 Spring 3.2 开发 Spring MVC Web 应用程序。我们会将网络应用程序部署到不同的客户。每个客户都可以使用服务接口的几种实现之一。

客户可能需要重置这些值,因此我们不能只是将实现硬连接到应用程序中,它需要是外部可配置的。 我们已经在使用客户特定的属性文件来设置简单的属性,例如字符串、数字等,但我想问的是如何设置接口的特定实现。

例如,

class MyClass {
 // this is straightforward
 @Value("${customer.propertyInPropertyFile}")
 private String customerSpecificString;

 // how to set the correct implementation for each customer?
 private ISomeService service;

}

如果有 4 个 ISomeService 实现,我们不能自动装配或显式设置 bean,因为这将在编译后的代码中设置 - 并且它需要在应用程序部署后可配置(可以重新启动应用程序,但如果需要)..

有人知道怎么做吗?使用 Spring EL 或配置文件会更好地执行此操作吗?

谢谢!

【问题讨论】:

  • 也看看spring profiles
  • 我查看了第一个链接,这是使用别名和 XML 配置。我希望使用 Java 注释配置,但也许这是不可能的,因为注释值是编译时常量。事情变得复杂了,在我们的 Spring 配置文件中,相同的 ${} 符号也标识了在 Maven 构建期间替换的变量,因此需要弄清楚如何区分在编译时和构建时替换的属性。

标签: spring properties dependency-injection


【解决方案1】:

所以,由于我想使用 Java 配置,我使用了以下解决方案:

@Configuration
@Profile("prod")
@EnableAsync
public class ProductionConfig extends BaseConfig
// inject property value which identifies theimplementation to use
Value("${service.impl}")
private String serviceName;

@Bean()

    public IRepository repository() {
        IRepository rc = null;
        if(StringUtils.isEmpty(serviceName)){
            rc =  new Impl1();
        } else if ("sword-mets".equals(serviceName)){
            rc = new Impl2();
        } else {
            rc = new Impl3();
        }
        log.info("Setting in repository implementation " + rc);
        return rc;

    }

因此,这并不像建议的使用别名的回复那样干净——Config 类需要知道所有可能的实现类——但是很简单,并且避免了只为这个 bean 使用 XML 配置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2011-02-22
    • 2016-09-27
    • 1970-01-01
    相关资源
    最近更新 更多