【问题标题】:How to access properties from messages.properties file in spring controller using annotation如何使用注释从spring控制器中的messages.properties文件中访问属性
【发布时间】:2021-05-19 09:16:54
【问题描述】:

如何使用注解从 spring 控制器中的 messages.properties 文件中访问属性。

请举个例子。

【问题讨论】:

标签: spring spring-mvc


【解决方案1】:

我使用了 MessageSource :

@Autowired
private MessageSource messageSource;

...

private EventByDate createDefaultEventByDate(String date, Long barId, String locale) {
    Event defaultEvent = new Event();
    Locale localeValue = new Locale(locale);
    defaultEvent.setTitle(messageSource.getMessage("default.event.title", null, "DefaultTitle", localeValue));
    defaultEvent.setText(messageSource.getMessage("default.event.text", null, "DefaultText", localeValue));
    ...
}

【讨论】:

    【解决方案2】:

    首先,您需要在 dispatcher-servlet.xml 文件中定义属性占位符,如下所示。

    <util:properties id="messageProperties" location="/messages.properties"/>
    

    您需要更改您的 messages.properties 文件的路径。

    然后你可以在@Value注解的帮助下访问属性文件值。

    private @Value("#{messageProperties['your.message.code']}") String message;
    

    希望这对您有所帮助。干杯。

    【讨论】:

    • 我试过了,但它似乎不起作用。我正在使用 spring 3.0。
    • 有什么问题??可以显示问题中的配置吗?
    • 也告诉我你把你的message.properties文件放在项目的什么地方。
    【解决方案3】:

    下面是dispatcher-servlet.xml

    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <util:properties id="messageProperties" location="/messages.properties"/></beans></pre>

    正如你提到的控制器,我对我的属性使用相同的代码。并且它无法解析@Value 注释。

    【讨论】:

      猜你喜欢
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多