P命名空间注入:
目的:简化set方法注入
使用p命名空间注入的前提条件包括两个:
c命名空间注入:
目的:简化构造方法
使用c命名空间注入的前提条件包括两个:
public class Dog {
//简单类型
private String name;
private int age;
//非简单类型
private Date birth;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
", birth=" + birth +
'}';
}
}
spring配置文件:spring-p.xml
第一步:在spring的配置文件头部添加p命名空间,xmlns:p=“http://www.springframework.org/schema/p”
第二步:使用 p:属性名
<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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dogBean" class="com.powernode.spring6.bean.Dog" p:name="小陈" p:age="3" p:birth-ref="birthBean">bean>
<bean id="birthBean" class="java.util.Date">bean>
beans>
测试类:
@Test
public void testSpringP(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-p.xml");
Dog dog = applicationContext.getBean("dogBean", Dog.class);
System.out.println(dog);
}
public class People {
private String name;
private int age;
private boolean sex;
//c命名空间注入办法是基于构造方法的
public People(String name, int age, boolean sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
'}';
}
}
spring配置文件:spring-c.xml
第一步:在spring的配置文件头部添加c命名空间,xmlns:c=“http://www.springframework.org/schema/c”
第二步:使用 c:参数名方式
也可以使用c:下标方式
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="peopleBean" class="com.powernode.spring6.bean.People" c:_0="小花" c:_1="20" c:_2="true">bean>
beans>
测试类:
@Test
public void testSpringC(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-c.xml");
People people = applicationContext.getBean("peopleBean", People.class);
System.out.println(people);
}
p命名空间本质上还是set注入,只不过p命名空间注入可以让spring配置变得更简单
c命名空间是简化构造方法注入的