依赖注入(DI)
- 依赖注入(Dependency Injection,DI)。
- 依赖 : 指Bean对象的创建依赖于容器 . Bean对象的依赖资源 .
- 注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配 .
构造器注入
我们在之前的03已经详细讲过了
settet注入 (重点)
要求被注入的属性 , 必须有set方法 , set方法的方法名由set + 属性首字母大写 , 如果属性是boolean类型 , 没有set方法 , 是 is .
pojo类
public class Address {
private String address;
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Address{" +
"address='" + address + '\'' +
'}';
}
}
public class Student {
private String name;
private Address address;
private String[] books;
private List hobbies;
private Map card;
private Set games;
private String wife;
private Properties info;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address.toString() +
", books=" + Arrays.toString(books) +
", hobbys=" + hobbies +
", card=" + card +
", games=" + games +
", wife='" + wife + '\'' +
", info=" + info +
'}';
}
public void setName(String name) {
this.name = name;
}
public void setAddress(Address address) {
this.address = address;
}
public void setBooks(String[] books) {
this.books = books;
}
public void setHobbies(List hobbies) {
this.hobbies = hobbies;
}
public void setCard(Map card) {
this.card = card;
}
public void setGames(Set games) {
this.games = games;
}
public void setWife(String wife) {
this.wife = wife;
}
public void setInfo(Properties info) {
this.info = info;
}
}
xml
红楼梦
水浒传
西游记
三国演义
听歌
码字
看电影
lol
魔兽
刀塔
rainbow
2014****
female
测试类
public class TestDI {
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student cong = (Student) context.getBean("cong");
System.out.println(cong.toString());
}
}
结果
Student{
name='cong',
address=Address{address='耀华里***'},
books=[红楼梦, 水浒传, 西游记, 三国演义], hobbys=[听歌, 码字, 看电影],
card={idCard=4408*******************,
countCard=6201***************,
studentCard=201*****},
games=[lol, 魔兽, 刀塔],
wife='null',
info={学号=2014****, 性别=female, 姓名=rainbow}
}
扩展,命名空间注入
pojo类
package com.cong.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 void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
beans.xml
注意要导入约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
测试类
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("user");
System.out.println(user.toString());
User user2 = (User) context.getBean("user2");
System.out.println(user2.toString());
}