`

Spring框架下资源属性的配置器类PropertyPlaceholderConfigurer

    博客分类:
  • java
阅读更多
   在applicationContext.xml里配置DBCP数据链接池时,dbcp.properties
dbcp.driverClassName = com.microsoft.sqlserver.jdbc.SQLServerDriver
dbcp.url = jdbc:sqlserver://192.168.1.132:1433;DatabaseName=HotelDB
dbcp.username = YXCK
dbcp.password = 123456
#连接池的最大数据库连接数,设为0表示无限制。 
dbcp.maxActive = 5
#数据库连接的最大空闲时间。超过此空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。
dbcp.maxIdle = 30
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。 
dbcp.maxWait = 10000
dbcp.defaultAutoCommit = true
#回收被遗弃的(一般是忘了释放的)数据库连接到连接池中。
dbcp.removeAbandoned = true
# 数据库连接过多长时间不用将被视为被遗弃而收回连接池中。
dbcp.removeAbandonedTimeout = 30
# 将被遗弃的数据库连接的回收记入日志。
dbcp.logAbandoned = true

applicationContext.xml配置
<!-- 定义数据源Bean,使用DBCP数据源实现 -->

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

<property name="driverClassName" value="${dbcp.driverClassName}" />  
    <property name="url" value="${dbcp.url}" />  
    <property name="username" value="${dbcp.username}" />  
    <property name="password" value="${dbcp.password}" />  
    <property name="maxActive" value="30"/><!--   value="${jdbc.maxActive}" />  -->
       <property name="maxIdle" value="${dbcp.maxIdle}" />  
       <property name="maxWait" value="${dbcp.maxWait}" />  
       <property name="defaultAutoCommit" value="${dbcp.defaultAutoCommit}"/>  
       <property name="removeAbandoned" value="${dbcp.removeAbandoned}"/>  
       <property name="removeAbandonedTimeout" value="${dbcp.removeAbandonedTimeout}"/>  
       <property name="logAbandoned" value="${dbcp.logAbandoned}"/>

</bean>以${}方式读取properties
文件里的配置,当为int类型时出现下面的错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.lang.String] to required type [int] for property 'maxActive'; nested exception is java.lang.NumberFormatException: For input string: "${jdbc.maxActive}"
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3830)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4337)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.lang.String] to required type [int] for property 'maxActive'; nested exception is java.lang.NumberFormatException: For input string: "${jdbc.maxActive}"
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:391)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1289)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
... 29 more
Caused by: java.lang.NumberFormatException: For input string: "${jdbc.maxActive}"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.lang.Integer.valueOf(Integer.java:553)
at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:157)
at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:114)
at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:382)
at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:358)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:173)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:138)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:386)
... 33 more

  发现时不能正确读取int类型的原因,经过变化关键词“applicationContext文件以${}方式读取properties文件的信息”搜索到,在Spring - applicationContext.xml配置文件中读取properties配置文件的内容可以使用org.springframework.beans.factory.config.PropertyPlaceholderConfigurer类。哈哈,看到希望继续变化关键词“org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”结果找到

http://thomaslee007.iteye.com/blog/167762
下面是其内容
Spring框架下PropertyPlaceholderConfigurer类
它的作用是一个资源属性的配置器,能够将BeanFactory的里定义的内容放在一个以.propertis后缀的文件中.



要了解这个类首先要弄清楚一个概念:bean factory post-processor
官方解释是这样的:
A bean factory post-processor is a java class which implements the
org.springframework.beans.factory.config.BeanFactoryPostProcessor interface. It is executed manually (in the case of the BeanFactory) or automatically (in the case of the ApplicationContext) to apply changes of some sort to an entire BeanFactory, after it has been constructed.
我理解的意思是这样的:
1.首先bean factory post-processor实现了org.springframework.beans.factory.config.BeanFactoryPostProcessor接口。
2.在BeanFactory的情况下它被手动的执行。
3.在ApplicationContext的条件下它会自动的执行。
4.最关键的一点是,是在一个类的实例被构造出来之后,对整个BeanFactory进行修改。

--------------------------------------------------------------------------------------------------------------------------------

Spring的框架中为您提供了一个 BeanFactoryPostProcessor 的实作类别: org.springframework.beans.factory.config.PropertyPlaceholderConfigurer。藉由这个类别,您可以将一些组态设定,移出至.properties档案中,如此的安排可以让XML定义档负责系统相关设定,而.properties档可以作为客户根据需求,自定义一些相关的参数。
来看一个Bean定义档的实际例子:

beans-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
      "http://www.springframework.org/dtd/spring-beans.dtd">

<beans> 
        <bean id="configBean"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location">
                <value>hello.properties</value>
            </property>
        </bean>

        <bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
            <property name="helloWord">
                <value>${onlyfun.caterpillar.helloWord}</value>
            </property>
        </bean>
</beans>
假设在helloBean中有许多依赖注入的属性,这些都是比较不常变动的属性,而其中helloWord会经常变动,可以透过hello.properties来简单的设定,而这个资讯已设定在configBean的location属性中:

hello.properties
onlyfun.caterpillar.helloWord=Welcome!
在helloBean的helloWord属性中,${onlyfun.caterpillar.helloWord}将会被hello.properties的helloWord所取代。

如果有多个.properties档案,则可以透过locations属性来设定,例如:

beans-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
      "http://www.springframework.org/dtd/spring-beans.dtd">

<beans> 
        <bean id="configBean"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <list>
                    <value>hello.properties</value>
                    <value>welcome.properties</value>
                    <value>other.properties</value>
   
                </list>
            </property>    
        </bean>

        <bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
            <property name="helloWord">
                <value>${onlyfun.caterpillar.helloWord}</value>
            </property>
            ...
        </bean>
</beans> ======================================PropertyPlaceholderConfigurer类就是bean factory post-processor的一种,它的作用是一个资源属性的配置器,能够将BeanFactory的里定义的内容放在一个以.propertis后缀的文件中。
例如---spring-context.xml----
<bean id="propertyConfigurer"     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
           <property name="locations">
               <list>
                   <value>/WEB-INF/jdbc.properties</value>
               </list>
           </property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName"><value>${driver}</value></property>
      <property name="url"><value>jdbc:${dbname}</value></property>
</bean>而实际的jdbc.propertis文件是
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root
而jdbc.propertis是怎样引用的呢: 将上边一段配置注册在web.xml中就可以了
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-context.xml</param-value>
</context-param>
当然,不要忘了spring的监听器注册
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
这样,一个简单的数据源就设置完毕了。
实际上,PropertyPlaceholderConfigurer起的作用就是将占位符指向的数据库配置信息放在bean中定义
的工具。



这样真正的原因明白了,需要PropertyPlaceholderConfigurer类,在applicationContext.xml加上
<!-- 配置PropertyPlaceholderConfigurer,将占位符指向的数据库配置信息放在bean中定义 -->

<bean name="customName"     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
             <property name="location">
                <value>/WEB-INF/dbcp.properties</value>
                        </property>

</bean>
问题解决。
分享到:
评论

相关推荐

    Spring PropertyPlaceholderConfigurer配置文件加载器集成ZooKeeper来实现远程配置读取

    在IT行业中,Spring框架是Java应用开发的核心组件,它提供了丰富的功能来简化应用程序的构建。在Spring中,`PropertyPlaceholderConfigurer`是一个非常重要的类,它用于处理属性文件中的占位符,将它们替换为实际的...

    Spring中PropertyPlaceholderConfigurer的使用

    在这种情况下,可以使用多个 `PropertyPlaceholderConfigurer` 来分散配置。例如: ```xml &lt;bean id="propertyConfigurerForProject1" class="org.springframework.beans.factory.config....

    属性占位符配置器

    ### 属性占位符配置器:Spring框架中的高级配置机制 #### 一、概念解析 在Spring框架中,**属性占位符配置器**(Property Placeholder Configurator)是一种强大的配置工具,它允许开发者在配置文件中使用占位符来...

    Spring实战之属性占位符配置器用法示例

    Spring框架中提供了属性占位符配置器(PropertyPlaceholderConfigurer),用于读取外部属性文件,并将其设置为Spring配置文件的数据。本文将详细介绍Spring实战之属性占位符配置器用法示例,结合实例形式分析了...

    Spring动态加载配置文件

    在Spring框架中,动态加载配置文件是一项重要的功能,它允许我们在程序运行时改变或更新配置,而无需重启应用。这在开发和生产环境中都具有很高的实用价值,尤其是在配置需要频繁调整或者希望实现热更新的场景下。...

    关于spring系统中多系统的配置

    通过设置`order`属性,可以控制不同配置器的执行顺序。`ignoreUnresolvablePlaceholders`属性用于控制是否忽略无法解析的占位符,默认情况下如果Spring无法找到占位符对应的属性值,将会抛出异常。 ### 总结 通过...

    Spring数据库连接等配置加密

    总的来说,Spring框架通过结合配置文件和解密器,可以有效地保护数据库连接等敏感信息,避免了因信息泄露带来的潜在风险。开发者应根据项目需求选择合适的加密算法和工具,并确保加密密钥的安全管理,以提升应用的...

    spring-reference

    Spring框架提供了多种方式来设置Bean的属性和协作者,例如通过构造器注入、设值注入或字段注入。 ##### 3.3.2 Bean 属性和构造器参数的详细说明 在Spring中,可以通过构造器注入的方式传递Bean的属性值或依赖关系。...

    spring整合三大框架笔记

    在现代Java Web开发中,Spring框架作为核心框架,常与其他多个框架进行整合,以实现更强大的功能和服务。本节将详细介绍如何将Spring与Struts2、Hibernate以及相关的连接池等组件进行整合。 #### 二、整合Struts2 ...

    配置spring

    在本文中,我们将深入探讨如何配置Spring框架,以及在整合Struts和iBatis时需要注意的关键步骤。Spring是一个广泛使用的Java应用程序框架,它提供了一种模块化和松耦合的方式来组织和管理应用组件。Struts则是一个...

    Struts+Spring+Ibatis整合框架搭建配置文档

    1. 添加Spring框架:首先,我们需要在`web.xml`中配置Spring的`ContextLoaderServlet`,它会在Web应用启动时加载`applicationContext.xml`配置文件。这一步确保了Spring容器的初始化。 ```xml &lt;param-name&gt;...

    Spring的log4j以及配置文件

    在Spring框架中,我们可以使用Spring的`PropertyPlaceholderConfigurer`来读取`log4j.properties`文件中的配置,并动态注入到应用中。这允许我们在不重启应用的情况下,通过修改外部的配置文件来调整日志级别和输出...

    spring mvc 读取配置文件

    在Spring MVC框架中,配置文件是整个应用的核心组成部分,它定义了bean的创建、依赖关系以及各种服务的配置。这篇博客“spring mvc 读取配置文件”将深入探讨如何在Spring MVC中读取和使用配置文件,以及相关工具的...

    Spring MVC 基本框架

    这些属性可以被 Spring 的 `PropertyPlaceholderConfigurer` 或 `Environment` 类读取,然后在 Spring 配置文件中引用,例如 `applicationContext.xml`: ```xml &lt;bean id="propertyConfigurer" class="org.spring...

    Spring-Reference_zh_CN(Spring中文参考手册)

    4.7.2. Application context构造器中资源路径的通配符 4.7.2.1. Ant风格的pattern 4.7.2.2. classpath*: 前缀 4.7.2.3. 其他关于通配符的说明 4.7.3. FileSystemResource 提示 5. 校验,数据绑定,BeanWrapper,与...

    图文搭建SSI(struts+spring+ibatis)框架

    同时,不要忘记在web.xml中配置Struts2和Spring的拦截器及监听器,以确保框架的正常工作。 在实际开发过程中,这样的框架组合提供了良好的分层架构,Struts2负责控制层,Spring处理依赖注入和事务管理,iBatis则...

    SPRING中文开发参考手册

    **Spring框架** 的设计哲学是“约定优于配置”,旨在减少应用程序中的耦合度,提高组件间的解耦程度。Spring 提供了多种方式来管理应用程序中的对象,从而简化了开发过程中的配置工作,并增强了代码的可测试性和可...

    Spring 配置学习文件

    在Spring框架中,配置文件起着至关重要的作用,它们定义了应用程序的组件以及它们之间的依赖关系。这里有两个主要的配置文件:`applicationContext-database.xml` 和 `applicationContext-pojo.xml`,分别关注于...

    spring-reference.pdf

    《Spring框架核心概念与应用详解》 一、Spring框架概览 Spring框架是Java平台上的一个开源框架,旨在简化企业级应用的开发。其核心功能包括依赖注入(DI)、面向切面编程(AOP)、数据访问/集成、事务管理、模型-...

Global site tag (gtag.js) - Google Analytics