九、装配bean--通过properties文件注入值

一、建立com.util下建立db.properties文件

name=root
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/bookmanage
pwd=123456

建立DBUtil.java

public class DBUtil {
    private String name;
    private String driver;
    private String url;
    private String pwd;

配置xml(配置方式1)

<!-- 引入properties文件 -->
    <context:property-placeholder location="classpath:com/util/db.properties"/>
    
    <!-- 使用占位符$表示properties文件中的变量 -->
    <bean id="dbutil" class="com.util.DBUtil">
        <property name="name" value="${name}"></property>
        <property name="url" value="${url}"></property>
        <property name="driver" value="${driver}"></property>
        <property name="pwd" value="${pwd}"></property>
    </bean>

配置xml(配置方式2)

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>com/util/db.properties</value>
            </list>
        </property>
    </bean>
    
    <!-- 使用占位符$表示properties文件中的变量 -->
    <bean id="dbutil" class="com.util.DBUtil">
        <property name="name" value="${name}"></property>
        <property name="url" value="${url}"></property>
        <property name="driver" value="${driver}"></property>
        <property name="pwd" value="${pwd}"></property>
    </bean>

 

二、如果要引入多个properties文件怎么引入

  注意:引入的多个properties文件中有多个名字相同的属性,则使用后引入的文件中的值

虽然不报错,但是我们如果要为了避免混淆,会给属性名前面加上文件名

db.name=root
db.driver=com.mysql.jdbc.Driver
db.url=jdbc\:mysql\://localhost\:3306/bookmanage
db.pwd=123456

那引用的时候就引用${db.xxx}了

 

配置多个properties文件

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>com/util/db.properties</value>
                <value>com/util/db2.properties</value>
            </list>
        </property>
    </bean>
<context:property-placeholder location="classpath:com/util/db.properties,classpath:com/util/db2.properties"/>

 

三、BUG

有时候配置的没问题,但是却有bug

Error creating bean with name 'org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0': Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions 

网上查了资料是,spring的命名空间有问题,我们需要在xml中统一spring的版本为3.0

<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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation=
    "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    ">

 

posted @ 2018-01-06 16:10  菜鸡蔡文姬  阅读(3276)  评论(0编辑  收藏  举报