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?
Multiple Properties can be accessed in Spring by either, @PropertySource( {"name1", "name2"} )
properties” property file, as it was automatically built inside the Spring boot application when the project is initially created. We can create and maintain multiple property files within “Resources” module, where we will be able to define different types of property values in different files.
If you can migrate to Spring 4.x the problem has been solved with the new @PropertySources annotation:
@PropertySources({ @PropertySource("/file1.properties"), @PropertySource("/file2.properties") })
Multiple Properties
can be accessed in Spring by either,
Example of @PropertySource,
@PropertySource({ "classpath:hibernateCustom.properties", "classpath:hikari.properties" })
Example of @PropertySources,
@PropertySources({ @PropertySource("classpath:hibernateCustom.properties"), @PropertySource("classpath:hikari.properties") })
After you specify properties
path you can access them through Environment
instance as you usually did
I was getting compilation error
as I was using property values to configure my app context. I tried all that I found through web but they did not work for me !
Until I configured Spring context as below,
applicationContext.setServletContext(servletContext); applicationContext.refresh();
Example
public class SpringWebAppInitializer implements WebApplicationInitializer{ @Override public void onStartup(ServletContext servletContext) throws ServletException { // Create the 'root' Spring application context AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); // register config class i.e. where i used @PropertySource applicationContext.register(AppContextConfig.class); // below 2 are added to make @PropertySources/ multi properties file to work applicationContext.setServletContext(servletContext); applicationContext.refresh(); // other config } }
For your information, I am using Spring 4.3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With