常见的@Configuration的几个实例在Spring中具有不同的@PropertySource [英] Several instances of a common @Configuration with different @PropertySource in Spring

查看:61
本文介绍了常见的@Configuration的几个实例在Spring中具有不同的@PropertySource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下配置文件:

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

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

    // getter setter
}

我想知道是否有一种方法可以自动接线两个 LanguageConfig 实例,每种语言一个.像这样的东西:

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;


}

谢谢.

推荐答案

不确定您要实现的目标是否可以实现,但是我为您提供了此解决方案.

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

您可以将它们放在一个文件中,而不是将每种语言都放在单独的文件中,例如 languages.properties ,然后使用 @PropertySource("classpath:language."属性")注释.之后,您可以使用 @ConfigurationProperties 注入这些属性.

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类应如下所示.

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

将这些 LanguageConfig 对象创建为bean,并向每个对象注入以 en sp 开头的属性.

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;

这篇关于常见的@Configuration的几个实例在Spring中具有不同的@PropertySource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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