Several instances of a common @Configuration with different @PropertySource in Spring

雨燕双飞 提交于 2020-02-06 08:47:46

问题


Hi I have the following configuration file :

@Configuration
@PropertySources({
    @PropertySource("classpath:english.properties"),
    @PropertySource("classpath:spanish.properties")
})
public class LanguageConfig {

    @Value(${hello})
    private String hello;

    // getter setter
}

I want to know if there is a way to Autowire two instances of LanguageConfig, one for each language. Something like :

public Myservice() {

    @Autowire
    @Qualifier("englishLanguage")
    private LanguageConfig englishConfig;


    @Autowire
    @Qualifier("spanishLanguage")
    private LanguageConfig spanishConfig;


}

Thank you.


回答1:


Not sure what you want to do can be achieved or not, but I offer you this solution.

Instead of having each language in separate files, you can put them in a single file, let's say languages.properties, and then add it using @PropertySource("classpath:language.properties") annotation. After that you can inject those properties using @ConfigurationProperties.

en.hello=Hello
sp.hello=Hola

LanguageConfig class should look like this.

public class LanguageConfig {

    private String hello;

    public String getHello() {
        return hello;
    }

    public void setHello(String hello) {
        this.hello = hello;
    }
}

Create those LanguageConfig objects as beans and inject properties starting with en and sp to each of them.

    @Bean
    @ConfigurationProperties("en")
    public LanguageConfig engConfig() {
        return new LanguageConfig();
    }

    @Bean
    @ConfigurationProperties("sp")
    public LanguageConfig spanishConfig() {
        return new LanguageConfig();
    }

Then you can use them easily.

    @Autowired
    @Qualifier("engConfig")
    LanguageConfig englishConfig;

    @Autowired
    @Qualifier("spanishConfig")
    LanguageConfig spanishConfig;


来源:https://stackoverflow.com/questions/59905548/several-instances-of-a-common-configuration-with-different-propertysource-in-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!