Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 253
bond Avatar asked Nov 29 '12 17:11

bond


People also ask

How do you inject property value into a class not managed by Spring?

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.

How do you get Spring context from a non Spring class?

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.

How property values can be injected directly into your beans in Spring boot?

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.


1 Answers

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")
like image 66
Benoit Wickramarachi Avatar answered Sep 20 '22 06:09

Benoit Wickramarachi