org.springframework.beans.factory.config.PropertyPlaceholderConfigurer

本文介绍如何在Spring框架中整合配置文件,并通过PropertyPlaceholderConfigurer类实现属性值的动态替换。同时,展示如何扩展该类以对配置信息进行加密处理,确保信息安全。


可以将上下文(配置文件)中的属性值放在另一个单独的标准java Properties文件中去。在XML文件中用${key}替换指定的properties文件中的值。这样的话,只需要对properties文件进行修改,而不用对xml配置文件进行修改。

从上图中,我们看到PropertyPlaceholderConfigurer实现了三个bean生命周期的接口:BeanFactoryAware & BeanNameAware & BeanFactoryPostProcessor。关于spring bean的生命周期,可以参考这里http://blog.youkuaiyun.com/gjb724332682/article/details/46767463

PropertyResourceConfigurer.postProcessBeanFactory()将properties文件中的属性进行merge,convert,最后调用PropertyPlaceholderConfigurer.processProperties()完成遍历bean定义替换属性占位符。


例子:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>WEB-INF/conf/xx.properties</value>
</property>
<property name="fileEncoding">
<value>UTF-8</value>
</property>
</bean>


<!--当然也可以引入多个属性文件,如: -->


<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/mail.properties</value>
<value>classpath:conf/sqlmap/jdbc.properties</value>
</list>
</property>
</bean>
<bean id="econsoleDS" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass">
<value>${jdbc.driverClassName}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>


除此之外,我们还可以扩展自这个类,用来诸如加解密配置信息等操作。如下:

import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.xxx.util.AESUtils;

public class DecryptPropertyPlaceholderConfigurer extends
		PropertyPlaceholderConfigurer {
	private String key = "xxxxxx";

	@Override
	protected void processProperties(
			ConfigurableListableBeanFactory beanFactory, Properties props)
			throws BeansException {
		try {
			String driverClassName = props.getProperty("driverClassName");
			if (driverClassName != null) {
				props.setProperty("driverClassName",
						AESUtils.aesDecrypt(driverClassName, key));
			}

			String url = props.getProperty("url");
			if (url != null) {
				props.setProperty("url", AESUtils.aesDecrypt(url, key));
			}

			String username = props.getProperty("username");
			if (username != null) {
				props.setProperty("username",
						AESUtils.aesDecrypt(username, key));
			}

			String password = props.getProperty("password");
			if (password != null) {
				props.setProperty("password",
						AESUtils.aesDecrypt(password, key));
			}
			super.processProperties(beanFactory, props);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BeanInitializationException(e.getMessage());
		}
	}
}
重写processProperties方法就可以。

debug' enabled. 2025-08-20 14:48:22.449 ERROR 36253 --- [ main] o.s.boot.SpringApplication : Application run failed org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'methodValidationPostProcessor' defined in class path resource [org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.class]: Unsatisfied dependency expressed through method 'methodValidationPostProcessor' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'shiroFilter' defined in class path resource [com/jk/moinc/framework/shiro/config/ShiroConfig.class]: Unsatisfied dependency expressed through method 'shiroFilter' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityManager' defined in class path resource [com/jk/moinc/framework/shiro/config/ShiroConfig.class]: Unsatisfied dependency expressed through method 'securityManager' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myRedisClusterConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.redis.maxIdle' in value "${spring.redis.maxIdle}" at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:799) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:540) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1341) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1181) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207) at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:229) at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:723) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:536) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:755) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) at org.springframework.boot.SpringApplication.refreshContext(SpringAp
最新发布
08-21
2025-05-14 14:23:55-[INFO ConfigurationLogger.java:104] ShardingRuleConfiguration: tables: addr_segm: actualDataNodes: dataSource.ADDR_SEGM_$->{3301..3311} logicTable: addr_segm tableStrategy: complex: algorithmClassName: com.zres.product.resmaster.space.zjyd.conf.CityCodeShardingAlgorithm shardingColumns: SEGM_ID,OLD_ID_EQP,REGION_ID addr_segm_access: actualDataNodes: dataSource.ADDR_SEGM_ACCESS_$->{3301..3311} logicTable: addr_segm_access tableStrategy: complex: algorithmClassName: com.zres.product.resmaster.space.zjyd.conf.CityCodeShardingAlgorithm shardingColumns: SEGM_ID,REGION_ID 2025-05-14 14:23:55-[INFO ConfigurationLogger.java:104] Properties: column-uppercase: 'true' sql.show: 'true' 2025-05-14 14:23:55-[INFO ShardingMetaDataLoader.java:131] Loading 2 logic tables' meta data. 2025-05-14 14:23:57-[INFO DefaultSingletonBeanRegistry.java:422] Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4d0ef07a: defining beans [frameWorkResEventHandlerDelegate,databaseObjectQueryFrameImpl,menuFrameService,namingServiceImpl,navigationConfService,propertyDataBizService,propertyDynamicMapperService,propertyPageData,propertyServiceImpl,dynamicQueryServiceImpl,frameQueryServiceImpl,pubRelationFrameService,treeService,afficheSerivceImpl,processStatThreadHolder,databaseQueryImpl,pubFunctionMenuService,fileUploadSerivceImpl,routeService,groupRoleSerivce,pubDataDimensionTypeService,pubEntityRoleService,pubRoleDimensionService,rolegrpService,roleQuyuService,roleSpecialityService,rolesService,staffRoleService,usergrpRolegrpService,vwPubDataDimensionService,departmentService,spcRegionService,staffStateService,staffWorkgrpService,titleService,workGroupService,safeStrategyService,frameWorkApplicationContext,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,zjydGisDataOperation,resQryOperation,resBaseQryOperation,addressOperation,districtQryOperation,keyAddrQryOperation,csvUtilOperation,addrBaseQryOperation,accessTypeQryOperation,nearaddrQryOperation,accessQryDataOperation,baseServiceOperation,syncIntfDataOperation,syncFullAddrOperation,syncManageOperation,zjydSolrDataOperation,syncIncreAddrOperation,syncITFOperation,esbDataOperation,syncAccessOperation,syncIntfService,syncDataFactoryService,interfaceLogService,zjydSolrService,esbService,accessQryService,addrSyncOperation,portNumSyncOperation,addrDataInStockOperation,portNumDataInStockOperation,addrInstockService,syncFilesNotifyService,portNumInstockService,tokenCacheManager,gwTokenFetcherImpl,const,spacePropertyService,spaceConfigService,spaceRestApiService,addrBatchAddService,roomPlaneService,addrRelDeviceService,addrManageService,accessQueryService,mergeAddressService,deleteResService,solrService,deviceSelectService,threeViewService,addrTreeService,deviceSelectDataOperation,solrDataOperation,addressAdjustDataOperation,deleteResDataOperation,addrRelDeviceDataOperation,threeViewDataOperation,spaceConfigDataOperation,accessQueryDataOperation,roomPlaneDataOperation,addrTreeDataOperation,addrManageDataOperation,spacePropertyDataOperation,addrBatchAddDataOperation,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,messageSource,jdbcTemplate,sqlSessionFactory,com.ztesoft.res.frame.orm.mybatis.mapper.ResMapperScannerConfigurer#0,sqlSessionTemplate,transactionManager,transactionInterceptor,org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator#0,com.ztesoft.res.frame.initialize.HttpRemoteSysConfigInitListener#0,loginController,com.ztesoft.res.frame.buz.ResProductComponentScan#0,cacheComponent,mongoDB,com.ztesoft.res.frame.tools.log.NoSqlLoggerInstance#0,loginTypeEnableAssertConfig,com.ztesoft.res.frame.filter.DefaultHasNameWebFilterChain#0,multiDataSourceWebFilter,com.ztesoft.res.frame.user.login.listener.DataSourceRouteSwitchOnLoginEventListener#0,roleDistributionServiceDynamic,staffServiceDynamic,com.ztesoft.res.frame.user.authority.listener.UserAuthorityListener#0,com.zres.product.resmaster.space.zjyd.conf.GisZjydConfData#0,com.zres.product.resmaster.space.zjyd.service.ZjydGisService#0,com.zres.product.resmaster.space.zjyd.conf.CSVConfData#0,com.zres.product.resmaster.space.zjyd.service.SyncAddrService#0,sResBaseQry,sAccessType,sAddrBaseQry,sDistrictQry,sKeyAddrQry,sNearaddrQry,sResQryCSV,sSolrQueryCSV,sSolrGetGuideResult,sQueryAccessInfo,sQrySegmAccess,projectConfBean,searchBean,com.ztesoft.res.frame.web.executor.protocol.ProtocolDispatchHandler#0,com.zres.product.resmaster.space.zjyd.conf.CSFFunctionCallApply#0,resJdbcTemplate,smartLocationServiceImpl,gaodeAPIServiceImpl,baiduAPIServiceImpl,addressServiceImpl,addressWebServiceDao,smartLocationRelDao,ossAddrSegmAccessDao,smartLocationSdeDao,ossDistrictDao,addressWebService,configDao,logDao,mapDao,configServiceImpl,logServiceImpl,ossAddrDao,ossAuthorityDao,ossCableDao,ossComDao,ossDelToProDao,ossEqpDao,ossGridDao,ossLineLengthDao,ossPipeDao,ossResQueryDao,ossAddrServiceImpl,ossAuthorityServiceImpl,ossComServiceImpl,ossDelToProServiceImp,ossGridServiceImpl,ossLineLengthServiceImpl,ossResQueryServiceImpl,ossResStatisticsServiceImpl,ossCableService,ossEqpService,ossPipeService,gisLineLengthDao,graphDao,graphUpdateDao,geoCoordConv,gisLineLength,graphDegree,mapStatisticDao,optCblDao,resConfigDao,resEditDao,resLineLengthDao,resQueryDao,synchronizationResDao,delPipeSectServiceImpl,mapStatisticServiceImpl,optCblServiceImpl,resEditServiceImpl,resLineLengthServiceImpl,resQueryServiceImpl,uploadFileService,queryClauseUtil,mapConfigDao,mapConfigServiceImpl,editTaskImpl,findTaskImpl,identifyTaskImpl,queryTaskImpl,geometryUtilityImpl,mapAPIConfigure,locationDao,mapAPIService,iMapAPIService,com.ztesoft.gis.module.location.service.impl.ZJESBCallApply#0,stGeometry,nativeJdbcExtrator,lobHandler,smartLocationService,iSmartLocationCSV,gisDataSource,resDataSource,dataSource,CSFConfig,cityCodeShardingAlgorithm,addr_segm_strategy,addr_segm_access_strategy,shardingDataSource,databaseObjectQueryFrameDao,menuFrameDao,namingFrameDao,navigationConfDao,propertyFrameDao,dynamicQueryDao,dynamicQueryDataDao,queryFrameDao,pubRelationFrameDao,treeDao,afficheDao,databaseQueryDao,pubFunctionMenuDao,fileUploadDao,routeDao,groupRoleDao,pubDataDimensionTypeDao,pubEntityRoleDao,pubRoleDimensionDao,rolegrpDao,roleQuyuDao,rolesDao,roleSpecialityDao,staffRoleDao,usergrpRolegrpDao,vwPubDataDimensionDao,loginUserDao,departmentDao,spcRegionDao,staffDao,staffStateDao,staffWorkgrpDao,titleDao,uosStaffDao,vwPubStaffDao,workGroupDao,safeStrategyDao,districtQryDao,resBaseQryDao,resQryDao,accessTypeQryDao,addrBaseQryDao,keyAddrQryDao,nearaddrQryDao,addrXAndYQryDao,accessQryDao,syncITFDao,syncAddrDao,interfaceLogDao,baseServiceDao,esbAddrDao,zjydSolrDao,addrInStockDao,portNumInSockDao,syncFilesNotifyDao,threeViewDao,addressAdjustDao,addrTreeDao,deleteResDao,addrRelDeviceDao,deviceSelectDao,addrManageDao,addrBatchAddDao,accessQueryDao,spaceConfigDao,addressDao]; root of factory hierarchy 2025-05-14 14:23:57-[ERROR ContextLoader.java:220] Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shardingDataSource': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.apache.shardingsphere.shardingjdbc.spring.datasource.SpringShardingDataSource]: Constructor threw exception; nested exception is java.sql.SQLException: Invalid column name at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:288) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
05-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值