spring中获取配置文件内容

来源:互联网 发布:java 金额转换成大写 编辑:程序博客网 时间:2024/06/05 11:14
在上一篇博客中,我们说了PropertyPlaceholderConfigurer类的作用,使用该类方便我们对配置文件的管理,然后我们在代码中如何获取属性文件的值呢?
既然PropertyPlaceholderConfigurer类可以加载properties文件,那自然我们可以自定义一个它的子类,在不影响它原来功能的情况下,存储我们需要的内容。
public MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{   private static Map myProperties;   @Override   protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,Properties props) throws BeansException{ super.processProerties(beanFactoryToProcess,props); myProperties=new HashMap();  for(Object key:props.keySet()){    String keySet = key.toString();    String value=props.getProperty(keySet);    myProperties.put(keySet,value);   }  }   public static Object getContextProperty(String name){      return myProperties.get(name);   } }      

有了这个类,我们就在BeanFactory中将原来的PropertyPlaceholderConfigurer类换成该类
<bean id="propertyConfigurer" class="MyPropertyPlaceholderConfigurer">    <property name="locations">          <list>             <value>classpath:config.properties</value>          <list>    </property></bean>
至此我们实现了在不影响原来的框架的情况下将属性文件的内容放到了myProperties中一份。

但是MyPropertyPlaceholderConfigurer作为一个bean是存在于容器中的,因此我们需要获得容器的上下文环境。
//@Component(或者在BeanFactory中配置)public class MyPropertiesUtil implements ApplicationContextAware{    public static final String KEY="propertyConfigurer";    private static ApplicationContext applicationContext;    @Override    public void setApplicationContext(Application applicationContext) throws BeansExcepton{     MyPropertiesUtil.applicationContext=applicationContext;    }      public static ApplicationContext getApplicationContext(){     return applicationContext;    }     public static String getValue(String key){      MyPropertyPlaceholderConfigurer cp=(MyPropertyPlaceholderConfigurer)applicationContext.getBean(KEY);      return cp.getApplicationContext(key).toString();     }}

至此我们已经写好了可以在代码中使用的Util类,但是无缘无故框架不会加载你自定义的类
因此我们需要加@Component注释或者在BeanFactory中加入
<bean class="MyPropertiesUtil"/>

自此,我们可以使用MyPropertiesUtil.getValue(key)来获得自定义文件中的内容,但是注意:这段代码不能在bean的属性中使用,比如某个bean中存在代码,定义属性private int pagesize=MyPropertiesUtil.getValue(key);这段代码会有时候对有时候错的情况,因为这两个bean(pagesize属性所在的类bean依赖myPropertiesUtil类的bean,但实际上myPropertiesUtil中ApplicationContext的注入是在所有bean创建之后的,所以会出现问题。)
0 0
原创粉丝点击