我正在使用以下配置设置。 @configuration类加载属性文件,然后生成一个arraylist,它以一种依赖于barUserList和fooUserList的类可以轻松消耗的方式提取属性文件的相关块。他们甚至不知道它来自属性文件。为了DI而Huzzah!
当我试图告诉Spring我想要哪一个时,我的问题就来了。 Foo类需要fooUserList,所以我应该能够使用@Qualifier注释,但是我找不到在XML之外设置/设置/限定符的方法。
所以我的问题是,如何在Javaland中为这两个Spring bean设置限定符?零XML配置对我来说是一个很大的目标。我知道你可以设置@name和Spring的@qualifier机制默认为@name,但是我想避免使用它。我不喜欢“默认”其他东西的东西。
我正在使用Spring 3.2.5.RELEASE
@Configuration
public class AppConfig {
@Bean
Properties loadProperties() throws IOException {
Properties properties = new Properties();
properties.load(new FileInputStream("checker.properties"));
return properties;
}
@Bean
@Autowired
ArrayList<String> barUserList(Properties properties) {
ArrayList<String> barUsernames = new ArrayList<String>();
Collections.addAll(barUsernames, properties.getProperty("site.bar.watchedUsernames", "").split(","));
return barUsernames;
}
@Bean
@Autowired
ArrayList<String> fooUserList(Properties properties) {
ArrayList<String> fooUsernames = new ArrayList<String>();
Collections.addAll(fooUsernames, properties.getProperty("site.foo.watchedUsernames", "").split(","));
return fooUsernames;
}
}
答案 0 :(得分:2)
一种方法是定义@Bean
的名称并在@Qualifier
上使用,如下所示:
@Bean(name="barUserList")
@Autowired
ArrayList<String> barUserList(Properties properties) {
ArrayList<String> barUsernames = new ArrayList<String>();
Collections.addAll(barUsernames, properties.getProperty("site.bar.watchedUsernames", "").split(","));
return barUsernames;
}
在使用中你可以有类似的东西:
// ...
@Autowired
@Qualifier("barUserList")
private List<String> userList;
// ...