简体   繁体   English

根据属性值自动装配Spring bean

[英]autowire a Spring bean based on the value of a property

nI am developing a Spring MVC web app using Spring 3.2. 我正在使用Spring 3.2开发Spring MVC Web应用程序。 We will deploy the web app to different customers. 我们将Web应用程序部署到不同的客户。 Each customer may use one of several implementations of a service interface. 每个客户可以使用服务接口的几种实现方式之一。

It's possible that the customer may need to reset these values, so we can't just hard-wire the implementation into the application, it needs to be externally configurable. 客户可能需要重置这些值,因此我们不仅可以将实现硬连线到应用程序中,还需要在外部进行配置。 We are already using customer-specific property files that for setting simple properties such as Strings, numbers etc, but I'm asking how to set a particular implementation of an interface. 我们已经在使用特定于客户的属性文件来设置简单属性,例如字符串,数字等,但是我在问如何设置接口的特定实现。

Eg, 例如,

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

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

}

If there are 4 implementations of ISomeService, we can't autowire, or explicitly set a bean, as this will then be set in the compiled code - and it needs to be configurable after the application is deployed ( it would be OK to restart the application though if need be).. 如果有4种ISomeService的实现,我们将无法自动装配或显式设置bean,因为这将在编译后的代码中进行设置-并且在部署应用程序后需要对其进行配置(重新启动即可)应用程序,如果需要的话。..

Does anyone know how to do this? 有谁知道如何做到这一点? Would this better be performed using Spring EL, or profiles? 使用Spring EL或Profile可以更好地执行此操作吗?

Thanks! 谢谢!

So, as I wanted to used Java configuration, I used the following solution: 因此,当我想使用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;

    }

So, this isn't quite as clean as the suggested reply using aliases - the Config class needs to know about all the possible implementation classes - but is simple and avoids having to use the XML config just for this bean. 因此,这不像使用别名的建议答复那么干净-Config类需要了解所有可能的实现类-但很简单,避免了仅为此bean使用XML config。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM