依赖注入(DI)
1、什么是依赖注入
- 依赖 : 指Bean对象的创建依赖于容器 . Bean对象的依赖资源 .
- 注入 : 指Bean对象所依赖的资源 , 由容器来设置和装配 .
把有依赖关系的类放到容器中,解析出这些类的实例,就是依赖注入。目的是实现类的解耦。
**例如:**Class A中用到了Class B的对象b,一般情况下,需要在A的代码中显式的new一个B的对象。采用依赖注入技术之后,A的代码只需要定义一个私有的B对象,不需要直接new来获得这个对象,而是通过相关的容器控制程序来将B对象在外部new出来并注入到A类里的引用中。这样做有什么好处呢?
解释:假如现在有N多个类,需要用到Class B,那就需要在类里面实例化N多次,这样对于后期的维护和管理都是不方便的,如果后期需求发生改变,那更改量有大很多。
2、 构造器注入
xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--ioc 创建对象的方式-->
<bean id="user" class="com.yyk.User">
<!--采用下标赋值-->
<!--<constructor-arg index="0" value="成龙"/>-->
<!--采用类型赋值-->
<constructor-arg type="java.lang.String" value="成龙"/>
<!--通过参数名赋值-->
<constructor-arg name="name" value="成龙>
<!--参数名为name,则有 name=“属性明”-->
</bean>
</beans>
3 、set注入(重点 必须理解)
1- 创建实体类
Student类 亦可以使用 Lombok 创建 get set 方法
package com.yyk.pojo;
import java.util.*;
/**
* @类名: Student.java
* @创建者:
* @版本: 1.0.0
* @类使用说明:
* @创建时间 2021年04月02日 10:32:00
*/
public class Student {
private String name;
private Address address;
private String[] book;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address.toString() +
", book=" + Arrays.toString(book) +
", hobbys=" + hobbys +
", card=" + card +
", games=" + games +
", 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[] getBook() {
return book;
}
public void setBook(String[] book) {
this.book = book;
}
public List<String> getHobbys() {
return hobbys;
}
public void setHobbys(List<String> hobbys) {
this.hobbys = hobbys;
}
public Map<String, String> getCard() {
return card;
}
public void setCard(Map<String, String> card) {
this.card = card;
}
public Set<String> getGames() {
return games;
}
public void setGames(Set<String> 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;
}
}
Address类
package com.yyk.pojo;
/**
* @类名: Assres.java
* @创建者:
* @版本: 1.0.0
* @类使用说明:
* @创建时间 2021年04月02日 10:33:00
*/
public class Address {
public String getAddres() {
return addres;
}
@Override
public String toString() {
return "Address{" +
"addres='" + addres + '\'' +
'}';
}
public void setAddres(String addres) {
this.addres = addres;
}
private String addres;
}
Lombok 依赖如下
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
2 - 配置spring IOC 容器
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--在Spring中创建对象,在Spring这些都称为bean
类型 变量名 = new 类型();
Holle holle = new Holle();
bean = 对象(holle)
id = 变量名(holle)
class = new的对象(new Holle();)
property 相当于给对象中的属性设值,让str="Spring"
-->
<!--要使用 类 必须在spring 容器中 注册-->
<bean id="address" class="com.yyk.pojo.Address">
<property name="addres" value="庆阳"></property>
</bean>
<!--使用set注入-->
<bean id="student" class="com.yyk.pojo.Student">
<!--第一种 普通值注入 value-->
<property name="name" value="杨永康"></property>
<!--第二种,Bean注入 ref-->
<property name="address" ref="address"></property>
<!--数组注入-->
<property name="book">
<array>
<value>红楼梦</value>
<value>平凡的世界</value>
<value>白鹿原</value>
</array>
</property>
<!-- List数组注入-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>敲代码</value>
<value>撩妹子</value>
<value>打篮球</value>
</list>
</property>
<!-- map注入-->
<property name="card">
<map>
<entry key="身份证" value="622827199711110911"/>
<entry key="银行卡" value="452565626528487845"/>
</map>
</property>
<!--set-->
<property name="games">
<set>
<value>LOL</value>
<value>CS</value>
<value>CSGO</value>
</set>
</property>
<!--null-->
<property name="wife">
<null/>
</property>
<!--Properties-->
<property name="info">
<props>
<prop key="driver">com.mysql.Driver</prop>
<prop key="url">127.0.0.1:3306/test</prop>
<prop key="username">root</prop>
<prop key="passwoed">1234</prop>
</props>
</property>
</bean>
</beans>
3 - 结果展示
@Test
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.toString());
}
Student{name='DDD', address=Address{addres='SSS'},
book=[红楼梦, 平凡的世界, 白鹿原], hobbys=[听歌, 敲代码, 撩妹子, 打篮球],
card={身份证=622827199711110911, 银行卡=452565626528487845},
games=[LOL, CS, CSGO], wife='null', info={url=127.0.0.1:3306/test,
driver=com.mysql.Driver, username=root, passwoed=1234}}
4 、扩展注入方式(使用使用p和c命名空间)
1- 使用p和c命名空间 必须先导入xml约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
2- 先新建实体类User 同样 凡是新建实体类都可以考虑使用lombok插件 依赖在上面
package com.yyk.pojo;
/**
* @类名: User.java
* @创建者:
* @版本: 1.0.0
* @类使用说明:
* @创建时间 2021年04月02日 11:30:00
*/
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;
}
}
3 - 新建spring 配置文件 Userbeans
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--在Spring中创建对象,在Spring这些都称为bean
类型 变量名 = new 类型();
Holle holle = new Holle();
bean = 对象(holle)
id = 变量名(holle)
class = new的对象(new Holle();)
property 相当于给对象中的属性设值,让str="Spring"
-->
<!-- p命名空间注入,可以直接注入属性-->
<bean id="user" class="com.yyk.pojo.User" p:name="yyk" p:age="18"></bean>
<bean id="user2" class="com.yyk.pojo.User" c:age="45" c:name="der" scope="prototype"></bean>
</beans>
4 - 测试
@Test
public void test2() {
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user2", User.class);
User user1 = context.getBean("user", User.class);
System.out.println(user==user1);
System.out.println(user.hashCode());
System.out.println(user1.hashCode());
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210424152454496.png#pic_center
5 、 bean 作用域
1 - 分类 bean作用域 可以分为五类
当在 Spring 中定义一个 时,你必须声明该 bean 的作用域的选项。例如,为了强制 Spring 在每次需要时都产生一个新的 bean 实例,你应该声明 bean 的作用域的属性为 prototype。同理,如果你想让 Spring 在每次需要时都返回同一个bean实例,你应该声明 bean 的作用域的属性为 singleton。
Spring 框架支持以下五个作用域,如果你使用 web-aware ApplicationContext 时,其中三个是可用的request、session和global session三种作用域
关于作用域 建议去看 狂神博客:https://mp.weixin.qq.com/s__biz=Mzg2NTAzMTExNg==&mid=2247484109&idx=1&sn=a3bc263536e84c93b9eb862cfa4da319&scene=19#wechat_redirect