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

泪湿孤枕 提交于 2019-12-07 10:47:27

问题


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?


回答1:


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



回答2:


For a more modern approach, that uses annotations and implements generics you can use this version, build upon Wickramarachi response:

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class StaticSpringApplicationContext implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        StaticSpringApplicationContext.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    public static <T> T getBean(String beanName, Class<T> requiredType) {
        return applicationContext.getBean(beanName, requiredType);
    }

}

Usage is as follow:

SpringJPAPersistenceChannel bean = StaticSpringApplicationContext.getBean(MyBean.class);


来源:https://stackoverflow.com/questions/13631052/how-to-get-property-from-spring-context-in-a-pojo-not-managed-by-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!