Spring注入空间
除了之前的构造注入、Set注入,Spring还提供了更简便的注入空间,读者可以根据自己喜好选择使用
一、p空间
p空间增加的约束
xmlns:p="http://www.springframework.org/schema/p"
示例
<bean id="user" class="com.lding.pojo.User" p:name="冷丁" p:age="18"> </bean>
二、c空间
注意:c空间需要写有参构造 ,c就是所谓的构造器注入
xmlns:c="http://www.springframework.org/schema/c"
示例
<bean id="user2" class="com.lding.pojo.User" c:age="18" c:name="lengding"></bean>
编写一个Demo
User.java
package com.lding.pojo;
public class User {
private String name;
private int age;
public User(){
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
userbean.xml
<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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- p命名空间注入,可以直接注入属性的值 property-->
<bean id="user" class="com.lding.pojo.User" p:name="冷丁" p:age="18">
</bean>
<!-- c命名空间注入,可以直接注入属性的值:property-->
<bean id="user2" class="com.lding.pojo.User" c:age="18" c:name="lengding"></bean>
</beans>
test.java
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
// User user = (User)context.getBean("user");
User user = context.getBean("user", User.class);
System.out.println(user);
User user2 = context.getBean("user2", User.class);
System.out.println(user2);
}