Reputation: 2542
I need to access properties from application.properties in messages.properties:
application.properties
max-size=3
messages.properties
alert.error=You can only save {max-size} items.
Not working:
{max-size}, #{max-size}, ${max-size}
I am aware of this thread, but I need it outside of any Java file.
Update: the maven approach works within application.properties files but not between application.properties and messages.properties. Shouldn't there be an order? If file A has key a but when file B is parsed first a is not available in B yet, is it?
Snippet from my pom.xml:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
</includes>
</resource>
"#{alert.error(${@environment.getProperty('max-size')})}"
Upvotes: 0
Views: 2979
Reputation: 44685
Either you replace it using build tools (Maven/Gradle/...), or you use a parameter in your message, like this:
alert.error=You can only save {0} items.
Now you can autowire your MessageSource
and retrieve your maxSize
:
@Autowired
private MessageSource messageSource;
@Value("${max-size}")
private int maxSize;
And then you can use it this way:
messageSource.getMessage("alert.error", new Object[]{maxSize}, locale);
This solution allows you to use your message for other sizes as well, rather than making it just 3.
If you want to use it in your views (eg. with Thymeleaf), you can do:
<p th:text="#{alert.error(${@environment.getProperty('max-size')})}"></p>
Upvotes: 4
Reputation: 11017
you can do via maven by invoking a resource plugin goal https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html
where messages.properties is placed in src/main/resources
<build>
<filters>
<filter>src/main/resources/application.properties</filter>
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
invoke mvn resources:resources
Upvotes: 1
Reputation: 7950
If you're building in maven you can filter the message.properties at build time.
https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html
Upvotes: 1