自定义PropertyPlaceHolder无法完成替换任务

 Spring默认的PropertyPlaceholderConfigurer只能加载properties格式的配置文件,现在需要完成让其支持可以从类似hadoop格式的xml配置文件中读取配置信息,并替换掉相关bean中的占位符,对其进行了扩展,具体扩展如下:

public class CustomPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
    private Resource[] locations;

    public void loadProperties(Properties props) throws IOException {
        if (this.locations != null) {
            PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
            for (int i = 0; i < this.locations.length; i++) {
                Resource location = this.locations[i];
                if (logger.isInfoEnabled()) {
                    logger.info("Loading properties file from " + location);
                }
                InputStream is = null;
                try {
                    is = location.getInputStream();
                    propertiesPersister.load(props, is);

                    Configuration conf = SquirrelConfiguration.create();
                    Map<String, String> map = conf.listAllConfEntry();  // 从squirrel-site.xml中读取配置信息
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        props.put(entry.getKey(), entry.getValue());
                    }
                } finally {
                    if (is != null) is.close();
                }
            }
        }
    }

    public void setLocations(Resource[] locations) {
        super.setLocations(locations);
        this.locations = locations;
    }

}




但是运行却一直报错,${jdbc_driver_name}没有被替换,通过查询发现,原来是在spring里使用org.mybatis.spring.mapper.MapperScannerConfigurer 进行自动扫描的时候,设置了sqlSessionFactory 的话,可能会导致PropertyPlaceholderConfigurer失效,也就是用${jdbc_driver_name}这样之类的表达式,将无法获取到properties文件里的内容。 导致这一原因是因为,MapperScannerConigurer实际是在解析加载bean定义阶段的,这个时候要是设置sqlSessionFactory的话,会导致提前初始化一些类,这个时候,
PropertyPlaceholderConfigurer还没来得及替换定义中的变量,导致把表达式当作字符串复制了。 但如果不设置sqlSessionFactory 属性的话,就必须要保证sessionFactory在spring中名称一定要是sqlSessionFactory ,否则就无法自动注入。又或者直接定义MapperFactoryBean ,再或者放弃自动代理接口方式。
可以如下方式修改:
<bean id="propertyConfigurer"  class="com.yowu.common.CustomPropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:important.properties</value>
            </list>
        </property>
     </bean>

	<!-- 配置线程池 -->
	<bean id="taskExecutor"
		class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
		<!-- 线程池维护线程的最少数量 -->
		<property name="corePoolSize" value="10" />
		<!-- 线程池维护线程所允许的空闲时间 -->
		<property name="keepAliveSeconds" value="0" />
		<!-- 线程池维护线程的最大数量 -->
		<property name="maxPoolSize" value="10" />
		<!-- 线程池所使用的缓冲队列 -->
		<property name="queueCapacity" value="0" />
	</bean>

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${squirrel_jdbc_driver}" />
		<property name="url" value="${squirrel_jdbc_url}" />
		<property name="username" value="${squirrel_jdbc_username}" />
		<property name="password" value="${squirrel_jdbc_password}" />
		<property name="validationQuery" value="select 1" />
		<property name="initialSize" value="5" />
		<property name="testWhileIdle" value="true" />
		<property name="maxIdle" value="20" />
		<property name="minIdle" value="5" />
		<property name="maxActive" value="50" />
		<property name="removeAbandonedTimeout" value="180" />
		<property name="maxWait" value="30000" />
	</bean>

    <bean id="ysqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" >
            <list>
                <value>classpath*:mybatis/*.xml</value>
            </list>
        </property>
    </bean>
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="ysqlSessionFactory"></constructor-arg>
        <constructor-arg index="1" value="BATCH"></constructor-arg>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.yowu.dao, com.yowu.app.repository.dao"/>
        <!--核心就是添加下面一句。后面那个属性是value,不是ref,切记-->
        <property name="sqlSessionFactoryBeanName" value="ysqlSessionFactory" />
    </bean>


通过查看MapperScannerConfigurer源码发现,其实有这么一段代码:

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
    if (this.processPropertyPlaceHolders) {
      processPropertyPlaceHolders();
    }

    Scanner scanner = new Scanner(beanDefinitionRegistry);
    scanner.setResourceLoader(this.applicationContext);

    scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
  }

  /*
   * BeanDefinitionRegistries are called early in application startup, before
   * BeanFactoryPostProcessors. This means that PropertyResourceConfigurers will not have been
   * loaded and any property substitution of this class' properties will fail. To avoid this, find
   * any PropertyResourceConfigurers defined in the context and run them on this class' bean
   * definition. Then update the values.
   */
  private void processPropertyPlaceHolders() {
大概意思是可以设置processPropertyPlaceHolders为true,强制让PropertyResourceConfigure执行下替换工作,大家不妨试一下,不失为一个优雅的解决方案。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值