Spring5学习深入学习理解依赖注入(DI)
「这是我参与2022首次更文挑战的第16天,活动详情查看:2022首次更文挑战」。
关于作者
- 作者介绍
🍓 博客主页:作者主页
🍓 简介:JAVA领域优质创作者🥇、一名在校大三学生🎓、在校期间参加各种省赛、国赛,斩获一系列荣誉🏆、阿里云专家博主、51CTO专家博主
🍓 关注我:关注我学习资料、文档下载统统都有,每日定时更新文章,励志做一名JAVA资深程序猿👨💻
8、依赖注入(DI)
-
依赖注入(Dependency Injection,DI)
-
依赖 : 指
Bean
对象的创建依赖于容器。Bean
对象的依赖资源 -
注入 : 指
Bean
对象所依赖的资源 , 由容器来设置和装配。
8.1构造器注入
同步到轻松入门SSM架构之Spring5的IOC创建对象方式
8.2 set注入(重点)
要求被注入的属性 , 必须有set方法 , set方法的方法名由set + 属性首字母大写 , 如果属性是boolean类型, 没有set方法 , 是 is .
测试pojo类:
Address.java
package com.spring.pojo;
/**
* @ProjectName: Spring5study
* @Package: com.spring.pojo
* @ClassName: Address
* @Author: 张晟睿
* @Date: 2022/2/2 12:42
* @Version: 1.0
*/
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.spring.pojo;
import java.util.*;
/**
* @ProjectName: Spring5study
* @Package: com.spring.pojo
* @ClassName: Student
* @Author: 张晟睿
* @Date: 2022/2/2 12:41
* @Version: 1.0
*/
public class Student {
private String name;
private Address address;
private String []course;
private List<String> hobbies;
private Map<String,String> books;
private Set<String> games;
private String girlfriends;
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[] getCourse() {
return course;
}
public void setCourse(String[] course) {
this.course = course;
}
public List<String> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
public Map<String, String> getBooks() {
return books;
}
public void setBooks(Map<String, String> books) {
this.books = books;
}
public Set<String> getGames() {
return games;
}
public void setGames(Set<String> games) {
this.games = games;
}
public String getGirlfriends() {
return girlfriends;
}
public void setGirlfriends(String girlfriends) {
this.girlfriends = girlfriends;
}
public Properties getInfo() {
return info;
}
public void setInfo(Properties info) {
this.info = info;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address +
", course=" + Arrays.toString(course) +
", hobbies=" + hobbies +
", books=" + books +
", games=" + games +
", girlfriends='" + girlfriends + '\'' +
", info=" + info +
'}';
}
}
1、常量注入
<?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">
<bean id="student" class="com.spring.pojo.Student">
<property name="name" value="厂长"/>
</bean>
</beans>
测试:
import com.spring.pojo.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @ProjectName: Spring5study
* @Package: PACKAGE_NAME
* @ClassName: MyTest
* @Author: 张晟睿
* @Date: 2022/2/2 12:57
* @Version: 1.0
*/
public class MyTest {
@Test
public void test1(){
ApplicationContext context= new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getName());
}
}
结果:
2、Bean注入
<!-- Bean注入方式-->
<bean id="address" class="com.spring.pojo.Address">
<property name="address" value="山西"/>
</bean>
<!-- 常量注入方式-->
<bean id="student" class="com.spring.pojo.Student">
<property name="name" value="厂长"/>
<!-- Bean注入方式-->
<!-- 这里需要注意这里需要映射到上面的addresss的Bean注入,所以使用ref来进行映射 -->
<property name="address" ref="address"/>
</bean>
3、数组注入
<!-- 数组注入方式-->
<property name="course">
<array>
<value>数据结构</value>
<value>数据库原理</value>
<value>操作系统</value>
<value>计算机网络</value>
</array>
</property>
4、List注入
<!-- List注入 -->
<property name="hobbies">
<list>
<value>打游戏</value>
<value>敲代码</value>
<value>旅游</value>
</list>
</property>
5、Map注入
<!-- Map注入 entry实体 key value进行注入 -->
<property name="books">
<map>
<entry key="10001" value="面向对象程序设计A"/>
<entry key="10002" value="面向对象程序设计B"/>
<entry key="10003" value="操作系统与组成原理"/>
</map>
</property>
6、Set注入
<!-- Set注入 value标签 -->
<property name="games">
<set>
<value>LOL</value>
<value>CF</value>
<value>梦三国</value>
</set>
</property>
7、Null注入
<!-- NUll注入 -->
<property name="girlfriends">
<null></null>
</property>
8、Properties注入
<!-- Properties注入 -->
<property name="info">
<props>
<prop key="driver">com.mysql.jdbc.Driver</prop>
<prop key="url">jdbc:mysql://localhost:3306?test</prop>
<prop key="username">root</prop>
<prop key="password">123456</prop>
</props>
</property>
测试:
import com.spring.pojo.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @ProjectName: Spring5study
* @Package: PACKAGE_NAME
* @ClassName: MyTest
* @Author: 张晟睿
* @Date: 2022/2/2 12:57
* @Version: 1.0
*/
public class MyTest {
@Test
public void test1(){
ApplicationContext context= new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.toString());
/*
* Student{name='厂长', address=Address{address='山西'},
* course=[数据结构, 数据库原理, 操作系统, 计算机网络],
* hobbies=[打游戏, 敲代码, 旅游],
* books={10001=面向对象程序设计A, 10002=面向对象程序设计B, 10003=操作系统与组成原理},
* games=[LOL, CF, 梦三国],
* girlfriends='null',
* info={password=123456, url=jdbc:mysql://localhost:3306?test, driver=com.mysql.jdbc.Driver, username=root}}
*
* */
}
}
测试结果:
8.3 拓展注入实现
User.java 【注意:这里没有有参构造器!】
package com.spring.pojo;
/**
* @ProjectName: Spring5study
* @Package: com.spring.pojo
* @ClassName: User
* @Author: 张晟睿
* @Date: 2022/2/2 14:04
* @Version: 1.0
*/
public class User {
private String name;
private int 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;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
1、P
命名空间注入 : 需要在头文件中假如约束文件
<!--导入约束 : xmlns:p="http://www.springframework.org/schema/p"-->
<!--P(属性: properties)命名空间 , 属性依然要设置set方法-->
<bean id="user" class="com.spring.pojo.User" p:name="厂长" p:age="20"/>
2、c
命名空间注入 : 需要在头文件中假如约束文件
<!--导入约束 : xmlns:c="http://www.springframework.org/schema/c"-->
<!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
<bean id="user2" class="com.spring.pojo.User" c:name="厂长" c:age="21"/>
发现问题:爆红了,刚才我们没有写有参构造!
解决:把有参构造器加上,这里也能知道,c 就是所谓的构造器注入!
测试:
@Test
public void test02() {
ApplicationContext context = new
ClassPathXmlApplicationContext("userbeans.xml");
User user = (User) context.getBean("user");
System.out.println(user);
}
8.4 Bean的作用域
在Spring中,那些组成应用程序的主体及由Spring IoC容器所管理的对象,被称之为bean。简单地讲, bean就是由IoC容器初始化、装配及管理的对象。
类别 | 说明 |
---|---|
singleton | 在Spring loC容器中仅存在个Bean实例, Bean以单例方式存在,默认值 |
prototype | 每次从容器中调用Bean时,都返回一个新的实例,即每次调用getBean()时,相当于执行new XxxBean() |
request | 每次HTTP请求都会创建一个新的Bean,该作用域仅适用于WebApplicationContext环境 |
session | 同一个HTTP Session共享一个Bean, 不同Session使 用不同Bean,仅适用于WebApplicationContext环境 |
几种作用域中,request、session、application作用域仅在基于web的应用中使用(不必关心你所采用的是什么web应用框架),只能用在基于web的Spring ApplicationContext环境。
8.4.1 Singleton
当一个bean
的作用域为Singleton
,那么Spring IoC
容器中只会存在一个共享的bean
实例,并且所有对bean
的请求,只要id
与该bean
定义相匹配,则只会返回bean
的同一实例。Singleton
是单例类型,就是 在创建起容器时就同时自动创建了一个bean
的对象,不管你是否使用,他都存在了,每次获取到的对象 都是同一个对象。注意,Singleton
作用域是Spring
中的缺省作用域。要在XML中将bean
定义成singleton
,可以这样配置
<!--P(属性: properties)命名空间 , 属性依然要设置set方法-->
<bean id="user" class="com.spring.pojo.User" p:name="厂长" p:age="20" scope="singleton"/>
测试类
@Test
public void test02() {
ApplicationContext context = new
ClassPathXmlApplicationContext("userbeans.xml");
User user = (User) context.getBean("user");
User user2 = (User) context.getBean("user");
System.out.println(user.hashCode());
System.out.println(user2.hashCode());
System.out.println(user==user2);
}
8.4.2 Prototype
当一个bean
的作用域为Prototype
,表示一个bean
定义对应多个对象实例。Prototype
作用域的bean
会导致在每次对该bean
请求(将其注入到另一个bean
中,或者以程序的方式调用容器的getBean()方法)时都会创建一个新的bean
实例。Prototype
是原型类型,它在我们创建容器的时候并没有实例化,而是当我们获取bean
的时候才会去创建一个对象,而且我们每次获取到的对象都不是同一个对象。根据经验,对有状态的bean
应该使用prototype
作用域,而对无状态的bean
则应该使用singleton
作用域。在 XML中将bean
定义成prototype
,可以这样配置:
<!--P(属性: properties)命名空间 , 属性依然要设置set方法-->
<bean id="user" class="com.spring.pojo.User" p:name="厂长" p:age="20" scope="prototype"/>
测试类
@Test
public void test02() {
ApplicationContext context = new
ClassPathXmlApplicationContext("userbeans.xml");
User user = (User) context.getBean("user");
User user2 = (User) context.getBean("user");
System.out.println(user.hashCode());
System.out.println(user2.hashCode());
System.out.println(user==user2);
}
8.4.2 Request
当一个bean
的作用域为Request
,表示在一次HTTP请求中,一个bean
定义对应一个实例;即每个HTTP 请求都会有各自的bean
实例,它们依据某个bean
定义创建而成。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean
定义:
<bean id="loginAction" class=com.spring.LoginController" scope="request"/>
针对每次HTTP请求,Spring
容器会根据loginController bean
的定义创建一个全新的loginController bean
实例,且该loginController bean
实例仅在当前HTTP request
内有效,因此可以根据需要放心的更改所建实例的内部状态,而其他请求中根据loginController bean
定义创建的实例,将不会看到这些特定于某个请求的状态变化。当处理请求结束,request
作用域的bean
实例将被销毁。
8.4.2 Session
当一个bean
的作用域为Session
,表示在一个HTTP Session
中,一个bean
定义对应一个实例。该作用域仅在基于web的Spring ApplicationContext
情形下有效。考虑下面bean
定义:
<bean id="user" class=com.spring.pojo.UserSession" scope="request"/>
针对某个HTTP Session
,Spring
容器会根据UserSession bean
定义创建一个全新的UserSession bean
实例,且该UserSession bean
仅在当前HTTP Session
内有效。与request
作用域一样,可以根据需要放心的更改所创建实例的内部状态,而别的HTTP Session
中根据UserSession
创建的实例,将不会看到这些特定于某个HTTP Session
的状态变化。当HTTP Session
最终被废弃的时候,在该HTTP Session
作用域内的bean
也会被废弃掉。
后语
厂长写博客目的初衷很简单,希望大家在学习的过程中少走弯路,多学一些东西,对自己有帮助的留下你的赞赞👍或者关注➕都是对我最大的支持,你的关注和点赞给厂长每天更文的动力。
对文章其中一部分不理解,都可以评论区回复我,我们来一起讨论,共同学习,一起进步!
微信(z613500)或者 qq(1016942589) 详细交流。