【问题标题】:Find message in mulitple properties files在多个属性文件中查找消息
【发布时间】:2018-01-05 22:45:00
【问题描述】:

在一个应用程序中,有多个属性文件用于管理异常消息、警报和其他一些文本,这些文件如下所示: - 核心消息.properties - 数据库异常.properties ......

在服务层中,可能发生了数据库调用,并且数据库返回了一个存在于属性文件中的键,我想获取该值并向用户界面层提出异常消息。

如果我知道 wich 属性文件中的键,代码将是这样的:

@Value("#{core['theExceptionKey']}") 
public String excpetionMessage; 

private void myMethod() {
throw new ExceptionClass(exceptionMessage);
}

我认为 spring 可以做到这一点,因为当我在 jsp 文件中使用 spring:message 标记时,spring 不知道 wwitch 文件中的密钥,但它会正确加载消息。

【问题讨论】:

标签: java spring resourcebundle


【解决方案1】:

您可以为此使用 Spring Environment 抽象。

首先您需要将属性源添加到您的 Java 配置文件中

@Configuration
@PropertySource("classpath:/com/mypacakge/core-message.properties")
public class AppConfig { 

或者如果您有多个属性文件

@Configuration
@PropertySources({
    @PropertySource("classpath:core-message.properties"),
    @PropertySource("classpath:database.properties")
}) 
    public class AppConfig { 

PropertySourceConfigurer 添加到您的 Java 配置文件中

 @Bean
 public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
 }

现在假设在您的core-message.properties 中有以下数据

message.name=Hello

您可以通过自动装配 Environment 抽象然后调用 env.getProperty() 在任何 bean 中检索此数据

@Autowired
Environment env;

public void m1(){
String message = env.getProperty("message.name")` // will return Hello

Environment 对象提供了配置属性源和解析属性的接口。它提供了从各种来源读取的便利:属性文件、系统环境变量、JVM 系统属性、servlet 上下文参数等,非常有用。例如:

    environment.getSystemProperties().put("message", "Hello");
    System.getProperties().put("message", "Hello");

    environment.getSystemProperties().get("message"); // retrieve property
    environment.getPropertySources() // allows manipulation of Properties objects

Spring Reference Documentation - Environment

【讨论】:

    【解决方案2】:

    要以编程方式获取密钥的值,您可以使用以下命令:

    @Autowired
    private Environment env;
    ...
    String something = env.getProperty("property.key.something");
    

    【讨论】:

    • 它给我的属性文件中存在的键 null
    猜你喜欢
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    相关资源
    最近更新 更多