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;}@Overridepublic 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:属性名
测试类:
@Testpublic 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;}@Overridepublic 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:下标方式
测试类:
@Testpublic 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命名空间是简化构造方法注入的