天天看點

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 + "]";
    }
    
    
    
}