BeanPostProcessor实现Environment获取到自定义properties解决过程

来源:互联网 发布:vs.php for vs2015 编辑:程序博客网 时间:2024/05/21 19:49

在一次新的需求之中,需要在一个实现BeanPostProcessor的类接口里面获取properties文件的所有属性,因为properties的加载器在Spring中是实现了BeanFactoryPostProcessor,BeanFactoryPostProcessor主要是对BeanDefine进行一些处理,并且他在Spring容器的生命周期,是在BeanPostProcessor执行之前的。所以在BeanPostProcessor应该是在properties加载完成之后再执行的。原理上是可以通过EnvironmentAware接口获取到environment的值。但是经过发现在我们系统中environment是没有自定义的properties包含的值。
后面通过重写PropertyPlaceholderConfigurer的loadProperties方法,添加下面代码可以把属性值写入Environment

MutablePropertySources sources = ((ConfigurableEnvironment) (springContext.getEnvironment())).getPropertySources();sources.addAfter(CONFIG_LOCATION, new PropertiesPropertySource(CONFIG_LOCATION, properties));

之前试验的方法:

第一次, 通过从SpringContext中获取所有PropertyPlaceholderConfigurer类型的bean,发现报错Bean ‘user’ of type [com.XXX.XXX.XXXX] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying),大致意思是说这个bean没有被所有的beanPostProcessor处理过。因为当前BeanPostProcessor依赖于这个Bean,所以这个Bean初始化的时候不会被当前的BeanPostProcessor处理。(失败)

第二次, 通过@Value把需要的属性先注入进来,然后进行处理。@Value实在populateBean方法里面注入值的。(成功,不灵活)

其实BeanPostProcessor和BeanFactoryPostProcessor在被使用的时候,都会被先初始化,再使用。以下附上Bean初始化的步骤
这里写图片描述

原创粉丝点击