Reputation:
I want to use Spring IoC to wire my services beans.
In some projects, configuration parameters come from properties file.
I'd like to implement this new project with the most similar approach as possible than the other ones so Spring XML application contexts are not aware that now configuration parameters come from a JMX instead of a properties file in the file system.
I'm getting the JMX configuarion parameters from an EJB in JBoss, but I'd really like to implement a server-independent solution that I can use without JBoss or even without EJBs.
Example of what I have in mind:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/application-context.xml");
applicationContext.replacePropertiesConfigurer( myCustomPropertiesFromJMX );
applicationContext.reloadApplicationContext();
SomeBean aBean = (SomeBean) applicationContext.getBean("someBean");
Of course, second and third line are invalid, but they're the way I imagine my desired solution.
Kind regards.
Upvotes: 2
Views: 1116
Reputation:
Thanks to Errandir for the guidance.
Thanks to Evgeniy Dorofeev too for his response in another question that asked the same.
The final code that suits my needs is next:
Create the context without factorying Spring beans yet (false constructor's second parameter):
ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"classpath:main-applicationContext.xml"}, false);
Create the properties wherever they come from:
Properties jmxConfig = new Properties();
jmxConfig.setProperty("parameterX", valueX);
Create programatically a PropertiesPlaceholderConfigurer and bind the previous custom properties we just created and bind it to the application context:
PropertySourcesPlaceholderConfigurer mapPropertySource = new PropertySourcesPlaceholderConfigurer();
mapPropertySource.setProperties(jmxConfig);
applicationContext.addBeanFactoryPostProcessor(mapPropertySource);
Finally, it's configured and now it's fine to create instances and get them:
applicationContext.refresh();
MyService myService = applicationContext.getBean("myService", MyService.class);
Upvotes: 2
Reputation: 5125
If you are using Spring 3.1.x you just have to implement PropertySource that will get properties from wherever you want. And then add it to your application environment:
ConfigurableApplicationContext applicationContext
= new ClassPathXmlApplicationContext("/application-context.xml");
PropertySource myPropertySource = new SomeImplementationOfPropertySource();
applicationContext.getEnvironment().getPropertySources().addFirst(myPropertySource);
I hope that I get your question right.
Upvotes: 1