I found there are two ways to do that:
1. use <util:properties>
1) Define your properties file test.properties
username=test
2) you need to define that in you applicationContext.xml to load the properties file.
<util:properties id="myProps" location="classpath:*.properties />
3) In you controller or other spring bean classes, you can use
@Controller public class MyController{ @Value("#myprops[username]") private String username; }I didn't test it. Just searched online.
2. use context:property-placeholder
1) test.properties
username=test2) Define context:property-placeholder in your context.xml.
<context:property-placeholder location="classpath*:youbar*.properties" ignore-resource-not-found="false" local-override="false" ignore-unresolvable="false" />Here I ran into a problem that I can't place the code above into applicationContext.xml, I have another youbarportlet.xml. The applicationContext.xml is loaded from web.xml from context-param, the second is like spring-servlet.xml.
I haven't entirely sure about the problem.
3) Access property through @Value annotation
@Controller public class MyController{ @Value("${username}") private String username; }
Then you can use the value anywhere in your controller. It's really convenient, right?
In case, you want to customize the value of properties.
greeting=Welcome, firstname lastname
firstname and lastname can't be defined in the properties. In this case, you need to use placeholder and then you MessageFormat to replace them.
greeting=Welcome, {0} {1}!
@Controllerpublic class MyController{ @Value("${greeting}") private String greeting; public void renderView(){ String newGreeting = MessageFormat.format(greeting, "test", "test"); } }
Then you'll see the value of newGreeting = Welcome, test test!