为什么spring <util:properties>不起作用</util:properties>

时间:2014-04-03 13:31:03

标签: java spring spring-mvc

我是Spring的新手,现在尝试建立与数据库的连接。 我配置了jdbc-config.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<tx:annotation-driven transaction-manager="txManager" />

<bean id="simpleJdbcTemplate"
    class="org.springframework.jdbc.core.JdbcTemplate">
    <constructor-arg ref="dataSource" />
</bean>

<bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<!-- the DataSource (parameterized for configuration via a PropertyPlaceHolderConfigurer) -->
<bean id="dataSource"
    class="org.springframework.jdbc.datasource.SingleConnectionDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" /> 

    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

</beans>

并在root-config.xml中导入属性:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-3.0.xsd">


  <util:properties id="appProperties" location="/WEB-INF/jdbc.properties" local-override="true"/>


<import resource="jdbc-config.xml" />

</beans>

当应用程序在服务器上部署时,我有以下错误:

org.springframework.beans.MethodInvocationException: 
Property 'driverClassName' threw exception; nested exception is
 java.lang.IllegalStateException: Could not load JDBC driver class [${jdbc.driverClassName}]

但是一切都很好,如果我使用

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    p:location="/WEB-INF/jdbc.properties" />

而不是

<util:properties ...

有人可以解释一下 - 为什么?

1 个答案:

答案 0 :(得分:2)

util:properties没有进行属性解析,只是创建了一个Properties bean。请参阅documentation

然而,PropertyPlaceholderConfigurer bean确实进行了属性解析。它是一个BeanFactoryPostProcessor,它操纵bean定义来解析任何属性占位符。