【问题标题】:Several instances of a common @Configuration with different @PropertySource in SpringSpring中具有不同@PropertySource的公共@Configuration的几个实例
【发布时间】:2020-01-25 01:14:14
【问题描述】:

您好,我有以下配置文件:

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

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

    // getter setter
}

我想知道是否有办法Autowire LanguageConfig 的两个实例,每种语言一个。类似的东西:

public Myservice() {

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


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


}

谢谢。

【问题讨论】:

  • 当您使用 Spring Boot 时,我建议您检查配置属性以便更好地处理此问题。
  • 也闻起来像最适合与 i18n 功能一起使用的东西,例如 MessageBundle

标签: java spring spring-boot dependency-injection


【解决方案1】:

不确定你想做的事能否实现,但我为你提供了这个解决方案。

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

en.hello=Hello
sp.hello=Hola

LanguageConfig 类应如下所示。

public class LanguageConfig {

    private String hello;

    public String getHello() {
        return hello;
    }

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

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

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

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

然后你就可以轻松使用了。

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

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

【讨论】:

  • 您可以将其嵌入到一个language 类中,其中ensplanguage 类的成员,该类的字段为hello,这可能会简化一点。不是最初的问题,但会更干净
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
相关资源
最近更新 更多