Using the new @PropertySource annotation in Spring 3.1, how can you access multiple property files with Environment?
Currently I have:
@Controller
@Configuration
@PropertySource(
name = "props",
value = { "classpath:File1.properties", "classpath:File2.properties" })
public class TestDetailsController {
@Autowired
private Environment env;
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
String file1Name = env.getProperty("file1.name","file1.name not found");
String file2Name = env.getProperty("file2.name","file2.name not found");
System.out.println("file 1: " + file1Name);
System.out.println("file 2: " + file2Name);
return "home";
}
The result is the correct file name from File1.properties, but file2.name not found. How can access File2.properties?
there are two different approaches:
the first one is to use the PropertyPlaceHolder in your applicationContext.xml:
beans-factory-placeholderconfigurer
the namespace to add is
xmlns:context="http://www.springframework.org/schema/context"If you want a direct access of a key to a String variable in your controller, use:
The second approach is to use the
util:propertiesin you applicationContext.xml:using the namesapce
xmlns:util="http://www.springframework.org/schema/util"schemaLocations:http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsdThen in your Controller:
If you want a value from the files, just use the method
getProperty(String key)