我怎么能有资格与使用注释配置文件变量的自动装配的财产? [英] How can I qualify an autowired property with a variable from a config file using annotations?

查看:147
本文介绍了我怎么能有资格与使用注释配置文件变量的自动装配的财产?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的具体问题是,我已经配置了两个bean实现了相同的接口和我有了这个接口的类型的属性第三豆。我注入使用配置属性的属性。因此,假设RemoteDataSource和LocalDataSource落实和的IDataSource有dao1的IDataSource类型的属性,我的XML配置可能是这样的:

My specific problem is that I have configured two beans that implement the same interface and I have a third bean that has a property of that interface's type. I inject the property using a config property. So, assuming RemoteDataSource and LocalDataSource implement IDataSource and dao1 has a property of type IDataSource, my XML config might look like this:

<bean id="datasource1" class="com.foo.RemoteDataSource">
  <property name="url">${url}</property>
</bean>
<bean id="datasource2" class="com.foo.LocalDataSource">
  <property name="path">${filepath}</property>
</bean>
<bean id="dao1" class="com.foo.MyDAO">
  <property name="dataSource">${datasource}</property>
</bean>

通过URL,文件路径和数据源正在包含的属性文件中定义。我们现在正在为注解驱动的配置一推,我不知道如何标注吾道将在属性文件中配置的数据源。我想这样做,但它显然是不允许的:

With url, filepath and datasource being defined in an included properties file. We are now making a push for annotation-driven configuration and I'm not sure how to annotate my dao to put the data source configured in the property file. I want to do something like this, but it is evidently not allowed:

@Autowired
@Qualifier("${datasource}")
public void setDataSource(IDataSource datasource) {...}

注:这是春季3

NB: this is spring 3

推荐答案

我的解决办法是这样的:

My solution was thus:

@Autowired
public void setDataProviders(Map<String,IDataProvider> dataProviders) {
    this.dataProviders = dataProviders;
}

@Autowired
@Value("${cms}")
public void setDataProviderName(String dataProviderName) {
    this.dataProviderName = dataProviderName;
}

public IDataProvider getDataProvider() {
    return dataProviders.get(dataProviderName);
}

注:我改变了命名为DataProvider的,从规范的DataSource这,这不是消除歧义。它实际上只是一个自制的REST客户端。

NB: I changed that naming to DataProvider to disambiguate from the canonical DataSource which this isn't. It's actually just a homemade REST client.

这篇关于我怎么能有资格与使用注释配置文件变量的自动装配的财产?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆