I have a property file that is configured within spring context xml file. I load values from the file fine. I am trying to load a property from that property file in a regular pojo which is not spring managed. Since Spring has already loaded that property, i was wondering if there is a way to get the value instead of me having to load the property file manually?
Load Configuration With Class Loader Instead of using third party implementations that support automatic application configuration loading, e.g. that implemented in Spring, we can use Java ClassLoader to do the same. We're going to create a container object that will hold Properties defined in resourceFileName.
If you need to access the Spring Application context from the above non spring class, then you should create a subclass of ApplicationContextAware. This subclass must override the setApplicationContext method and Spring passes the associated application context in this method.
Property values can be injected directly into your beans using the @Value annotation, accessed via Spring's Environment abstraction or bound to structured objects via @ConfigurationProperties . Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values.
You can access the Spring context in a static way if your pojo is not managed by Spring.
Add a bean to your application xml:
<bean id="StaticSpringApplicationContext" class="com.package.StaticSpringApplicationContext"/>
Create a class:
public class StaticSpringApplicationContext implements ApplicationContextAware {
private static ApplicationContext CONTEXT;
public void setApplicationContext(ApplicationContext context) throws BeansException {
CONTEXT = context;
}
public static Object getBean(String beanName) {
return CONTEXT.getBean(beanName);
}
}
Then you can acces any Spring bean from your POJO using:
StaticSpringApplicationContext.getBean("yourBean")
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