K.Vu
K.Vu

Reputation: 193

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

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.

Upvotes: 0

Views: 776

Answers (1)

Mansur
Mansur

Reputation: 1829

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;

Upvotes: 4

Related Questions