Spring DI(依赖注入)
1.依赖注入(DI)
- 依赖注入(Dependency Injection,DI)。
- 依赖 : 指Bean对象的创建依赖于容器 . Bean对象的依赖资源 .
- 注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配 .
1.1 构造器注入
1.2 Set方式注入(重点)
依赖注入:set注入
依赖:bean对象的创建依赖于容器
注入:bean对象中所有的属性,由容器来注入
普通值注入,基于set注入
环境搭建
Address类
package com.zhang.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类
package com.zhang.pojo;
import java.util.*;
public class Student {
private String name;
private Address address;
private String[] books;
private List hobbys;
private Map card;
private Set game;
private String wife;
private Properties info;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address +
", books=" + Arrays.toString(books) +
", hobbys=" + hobbys +
", card=" + card +
", game=" + game +
", wife='" + wife + '\'' +
", info=" + 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 Map getCard() {
return card;
}
public void setCard(Map card) {
this.card = card;
}
public Set getGame() {
return game;
}
public void setGame(Set game) {
this.game = game;
}
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;
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
1.2.1 常量注入
1.2.2 数组注入
红楼梦
西游记
水浒传
1.2.3 列表注入
听歌
看电影
敲代码
1.2.4 map注入
1.2.5 set注入
LOL
COC
BOB
1.2.6 null注入
//方式1
//方式二
1.2.7 properties注入
com.jdbc.cj.JDBC
localhost:3306
root
123456
1.2.8 bean注入(引用)
完善注入信息
1.3 拓展方式注入
p命名和c命名不能直接使用,需要在头部导入xml约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
package com.zhang.pojo;
public class User {
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", 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;
}
}
p命名注入 property
c命名空间注入 constructor
注意点:p命名和c命名不能直接使用,需要导入xml约束