9

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

请举个例子。

4

3 回答 3

18

我使用了 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));
    ...
}
于 2014-08-17T18:37:14.290 回答
0

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

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

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

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

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

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

于 2013-01-10T07:52:52.477 回答
0

message.properties 文件位置

以下是 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-上下文.xsd ">

<context:annotation-config/> <util:properties id="messageProperties" location="/messages.properties"/></beans></pre>

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

于 2013-01-11T06:14:01.940 回答