- 注入的三种方式
- Set方式注入(重点)
- 基本步骤
- 1.复杂类型
- 2.真实测试对象
- 3.bean.xml
- 4.测试
- 拓张方式注入(P,C命名空间)
注入的三种方式依赖注入的解读:
依赖:bean对象的创建依赖于容器;
注入:bean对象中的所有属性,由容器来注入。
Set方式注入(重点) 基本步骤构造器注入(和之前的一样);Set方式注入;拓展方式注入
1.复杂类型1.编写复杂类型
2.编写真实测试对象
3.编写beans.xml
4.测试
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Address{" +
"address='" + address + ''' +
'}';
}
}
2.真实测试对象
public class Student {
public String name;
private Address address;
private String[] books;
private List hobbys;
private Set game;
private Map card;
private Properties info;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String[] getBooks() {
return books;
}
public void setBooks(String[] books) {
this.books = books;
}
public List getHobbys() {
return hobbys;
}
public void setHobbys(List hobbys) {
this.hobbys = hobbys;
}
public Set getGame() {
return game;
}
public void setGame(Set game) {
this.game = game;
}
public Map getCard() {
return card;
}
public void setCard(Map card) {
this.card = card;
}
public Properties getInfo() {
return info;
}
public void setInfo(Properties info) {
this.info = info;
}
@Override
public String toString() {
return "Student{" +
"name=" + name + "n" +
", address=" + address +"n"+
", books=" + Arrays.toString(books) +"n"+
", hobbys=" + hobbys +"n"+
", game=" + game +"n"+
", card=" + card +"n"+
", info=" + info +"n"+
'}';
}
}
3.bean.xml
数组注入
Spring企业级开发 Java开发手册 码出高效
List注入
看电影 听音乐 篮球
Set注入
LOL LOLM and so on...
Map注入
Properties注入
20211101 男 优
整合
4.测试Spring企业级开发 Java开发手册 码出高效
看电影 听音乐 篮球 LOL LOLM and so on... 20211101 男 优
public class MyTest {
@Test
public void test01(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = context.getBean("student", Student.class);
System.out.println(student.toString());
}
}
结果为:
使用p命名注入,可以直接注入属性的值:property
使用步骤:1.导入xml约束;2.p:name="name"的形式就行赋值
xmlns:p="http://www.springframework.org/schema/p"
使用c命名注入,可通过有参构造进行注入:constructs-args
使用步骤:1.导入xml约束;2.c:name="name"的形式就行赋值
xmlns:c="http://www.springframework.org/schema/c"



