天天看点

Spring IOC容器 p名称空间注入属性值

使用p命名空间

为了简化xml文件的配置,越来越多的xml文件采用属性而非子元素配置信息

spring从2.5版本开始引入了一个新的p命名空间,可以通过

元素属性的方式配置bean的属性

使用p命名空间后,基于xml的配置方式将进一步简化

在头文件中加入

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:util="http://www.springframework.org/schema/util"
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/util
     http://www.springframework.org/schema/util/spring-util.xsd
  "
  >      
<!-- 配置单例的集合bean ,以供多个bean进行引用 -->
    <util:list id="cars">
        <ref bean="car"/>
        <ref bean="car2"/>
    </util:list>
     <!-- 通过p命名空间为bean的属性赋值,需要先导入p命名空间 -->
    <bean id="person3" class="com.beans.collection.Person" p:name="queen"
    p:age="44" p:cars-ref="cars"></bean>      
package com.beans.collection;

import java.util.List;
import java.util.Map;

public class Person {
   
    private String name;
    private int age;
    private List<Car> cars;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    
    public List<Car> getCars() {
        return cars;
    }
    public void setCars(List<Car> cars) {
        this.cars = cars;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", cars=" + cars + "]";
    }
    
    
    
}