Spring2.5 p名称空间的使用

21 min read

spring2.5以后,为了简化setter方法属性注入,引用p名称空间的概念,可以将<property> 子元素,简化为<bean>元素属性配置。

  1. 属性字段提供 set 方法

    public class UserService {
    
        // 业务对象UserDao set注入(提供set方法)
        private UserDao userDao;
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
    
        // 常用对象String  set注入(提供set方法)
        private String host;
        public void setHost(String host) {
            this.host = host;
        }
    }
    
  2. 在配置文件 spring.xml 引入 p 名称空间

    xmlns:p="http://www.springframework.org/schema/p"
    
    <?xml version="1.0" encoding="UTF-8"?>
    <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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd">
    
    	<bean id="userDao" class="com.xxxx.dao.UserDao"></bean>
        <!--
    		p:属性名:="xxx"		引入常量值
    		p:属性名-ref:="xxx"	引入其他Bean对象的id属性值
    	-->
        <bean id="userService" class="com.xxxx.service.UserService" 
            p:userDao-ref="userDao" 
            p:host="127.0.0.1" />
    
    </beans>