如何在不受Spring管理的pojo中从Spring Context获取Property? [英] How to get Property from Spring Context in a pojo not managed by spring?

查看:179
本文介绍了如何在不受Spring管理的pojo中从Spring Context获取Property?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在Spring上下文xml文件中配置的属性文件.我很好地从文件中加载了值. 我试图从不是Spring管理的常规pojo中从该属性文件中加载一个属性.由于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?

推荐答案

如果您的pojo不受Spring管理,则可以静态方式访问Spring上下文.

You can access the Spring context in a static way if your pojo is not managed by Spring.

将bean添加到您的应用程序xml:

<bean id="StaticSpringApplicationContext" class="com.package.StaticSpringApplicationContext"/>

创建课程:

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);
      }

}

然后,您可以使用以下命令从POJO中访问任何Spring bean:

StaticSpringApplicationContext.getBean("yourBean")

这篇关于如何在不受Spring管理的pojo中从Spring Context获取Property?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆