문제

I'm using the below configuration setup. The @configuration class loads the property file, and then there is an arraylist that produced which extracts the relevant chunks of the property file in a way that the classes that depend on barUserList and fooUserList can consume easily. They don't even know that it came from a property file. Huzzah for DI!

My problem comes when I try to tell Spring which one of these I want. Class Foo wants fooUserList so I should be able to use the @Qualifier annotation, but I can't find a way to /set/ the qualifier outside of XML.

So my question is this, how do I set the Qualifier for these two Spring beans in Javaland? Zero XML config is a big goal for me. I know that you can set @name and the @qualifier mechanism for Spring will default to the @name, but I'd like to avoid using that. I don't like things that "default to" other things.

I'm using 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;
    }
}
도움이 되었습니까?

해결책

One way could be by defining a name for the @Bean and using it on @Qualifier as follows:

@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;
}

and within the use you could have something like:

// ...
@Autowired
@Qualifier("barUserList")
private List<String> userList;
// ...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top