Search code examples
springpropertiespojo

How to get Property from Spring Context in a pojo not managed by spring?


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?


Solution

  • 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")