DI依赖注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中所有属性由容器来注入
DI注入的几种方式:
-
构造器注入-详见:
- set方式注入(重点)
-
其他拓展方式注入
可以利用p命名空间和c命名空间进行注入
set方式注入
Address.java:
package com.kakafa.pojo;
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 + '\'' +
'}';
}
}
Student.java:
package com.kakafa.pojo;
import java.util.*;
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;
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 getHobbies() {
return hobbies;
}
public void setHobbies(List hobbies) {
this.hobbies = hobbies;
}
public Map getCard() {
return card;
}
public void setCard(Map card) {
this.card = card;
}
public Set getGames() {
return games;
}
public void setGames(Set games) {
this.games = games;
}
public String getWife() {
return wife;
}
public void setWife(String wife) {
this.wife = wife;
}
public Properties getInfo() {
return info;
}
public void setInfo(Properties info) {
this.info = info;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address.toString() +
", books=" + Arrays.toString(books) +
", hobbies=" + hobbies +
", card=" + card +
", games=" + games +
", wife='" + wife + '\'' +
", info=" + info +
'}';
}
}
bean.xml:
<?xml version="1.0" encoding="UTF-8"?>
红楼梦
水浒传
三国演绎
西游记
看书
打乒乓球
游泳
听歌
王者荣耀
英雄联盟
使命召唤
大一
一班
test:
import com.kakafa.pojo.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
Student student = (Student)context.getBean("student");
System.out.println(student.toString());
/*
* Student{
* name='许魏洲',
* address=Address{address='地球村2662号'},
* books=[红楼梦, 水浒传, 三国演绎, 西游记],
* hobbies=[看书, 打乒乓球, 游泳, 听歌],
* card={学号=202201064455, 学院=音乐学院},
* games=[王者荣耀, 英雄联盟, 使命召唤],
* wife='null',
* info={班级=一班, 年级=大一}}
* */
}
}