前言:
小伙伴们,大家好,我是狂奔の蜗牛rz,当然你们可以叫我蜗牛君,我是一个学习Java半年多时间的小菜鸟,同时还有一个伟大的梦想,那就是有朝一日,成为一个优秀的Java架构师。
这个Spring基础学习系列是用来记录我学习Spring框架基础知识的全过程 (这个系列是参照B站狂神的Spring5最新教程来写的,由于是之前整理的,但当时没有发布出来,所以有些地方可能有错误,希望大家能够及时指正!)
之后我将会以一天一更的速度更新这个系列,还没有学习Spring5框架的小伙伴可以参照我的博客学习一下;当然学习过的小伙伴,也可以顺便跟我一起复习一下基础。
最后,希望能够和大家一同进步吧!加油吧!少年们!
废话不多说,让我们开始今天的学习内容吧,今天我们来到了Spring基础学习的第六站:依赖注入!
6.依赖注入
依赖注入的方式主要分为三种形式:分别是构造器注入、set方法注入 和 c命名空间或者p命名空间注入
6.1 构造器注入
6.1.1 使用无参构造创建对象
1.概述和步骤
1-1 概述
构造器实例化:它是指Spring容器通过Bean对应类中的默认的构造函数来实例化Bean
1-2 步骤
- 首先创建一个User实体类对象,定义个name属性,然后生成它的无参构造以及get和set方法
- 接着编写applicationContext.xml配置文件,注册bean节点,配置两个属性:id和class:id是user对象的唯一标识名,class是User类的全限定名;然后在bean标签中配置property,有name和value两个属性:name是User类的字段名称,value是对应字段的属性值 (相当于key-value)
- 最后编写测试类,定义配置文件路径,然后通过ApplicationContext加载配置文件,并且实例化Bean对象,调用getBean方法获取Spring容器中的通过无参构造创建的实例化Bean
2. 编写User实体类
package com.kuang.pojo;
public class User {
private String name;
//无参构造方法
public User() {
System.out.println("User的无参构造");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("name="+name);
}
}
3.编写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">
<!--默认使用无参构造创建对象-->
<bean id="user" class="com.kuang.pojo.User">
<property name="name" value="罗翔老师"/>
</bean>
</beans>
4. 编写MyTest测试类
public class MyTest {
public static void main(String[] args) {
//ApplicationContext在加载配置文件时,对Bean进行实例化
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//对象都在Spring容器,要使用直接取出来使用即可
User user = (User) context.getBean("user");
//调用show方法显示用户名
user.show();
}
}
5.测试结果
6.1.2 使用有参构造创建对象
1. 编写beans.xml配置文件
1-1 使用下标赋值
- 在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">
<!--第一种:下标赋值 -->
<bean id="user" class="com.kuang.pojo.User">
<constructor-arg index="0" value="罗翔说刑法"/>
</bean>
</beans>
1-2 通过类型创建
- 在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">
<!--第二种方式:通过类型创建-->
<bean id="user" class="com.kuang.pojo.User">
<constructor-arg type="java.lang.String" value="luoxiang"/>
</bean>
</beans>
1-3 通过参数名来设置
- 在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">
<!--第三种方式:直接通过参数名来设置-->
<bean id="user" class="com.kuang.pojo.User">
<constructor-arg name="name" value="罗翔"/>
</bean>
</beans>
2. 编写MyTest测试类
public class MyTest {
public static void main(String[] args) {
//获取beans.xm配置文件,拿到Spring的容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//从IOC容器中获取Bean
User user = (User) context.getBean("user");
//获取用户名字信息
user.show();
}
}
3. 测试结果
3-1 使用下标赋值
结果:获取到name值为“罗翔说刑法”的用户信息!
3-2 通过类型创建
结果:获取到name值为“luoxiang”的用户信息!
3-3 通过参数名来设置
结果:获取到name值为“罗翔”的用户信息!
6.2 Set方法注入【重点】
6.2.1 依赖注入:set注入
- 依赖 :bean对象的创建依赖于容器
- 注入:bean对象中所有属性,由容器来注入
6.2.2 基本环境搭建
1.编写Address实体类
- Address实体类属于简单类型
package com.kuang.pojo;
public class Address {
private String address; //地址
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
2.编写Student实体类
- Student实体类属于复杂类型
public class Student {
private String name; //姓名
private Address address; //地址
private String[] books; //书本
private List<String> hobbies; //爱好
private Map<String,String> card; //银行卡
private Set<String> 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<String> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
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;
}
//toString方法
@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 +
'}';
}
}
3.编写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">
<bean id="student" class="com.kuang.pojo.Student">
<!--第一种:普通值注入,value-->
<property name="name" value="张楚岚"/>
</bean>
</beans>
4.编写MyTest测试类
public class MyTest {
public static void main(String[] args) {
//读取上下文,获取Spring的IOC容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//通过IOC容器获取Bean信息
Student student = (Student) context.getBean("student");
//打印学生的姓名信息
System.out.println(student.getName());
}
}
5.测试结果
结果:成功查询到name值为"张楚岚"的学生信息!
6.2.3 完善注入信息
1.修改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">
<!--第一种:普通值注入,value-->
<bean id="address" class="com.kuang.pojo.Address">
<property name="address" value="北京"></property>
</bean>
<!--第一种:普通值注入,value-->
<bean id="student" class="com.kuang.pojo.Student">
<property name="name" value="张楚岚"/>
<!--第二种:Bean注入,ref-->
<property name="address" ref="address"></property>
<!--第三种:数组String[]-->
<property name="books">
<array>
<value>《西游记》</value>
<value>《三国演义》</value>
<value>《水浒传》</value>
<value>《红楼梦》</value>
</array>
</property>
<!--第四种:List集合-->
<property name="hobbies">
<list>
<value>听音乐</value>
<value>看电影</value>
<value>敲代码</value>
</list>
</property>
<!--第五种:Map集合:键值对-->
<property name="card">
<map>
<entry key="身份证" value="410221199908068564"></entry>
<entry key="银行卡" value="651254386506"></entry>
</map>
</property>
<!--第六种:Set集合-->
<property name="games">
<set>
<value>英雄联盟</value>
<value>绝地求生</value>
<value>魔兽争霸</value>
</set>
</property>
<!--第七种:String:字符串,值为空-->
<property name="wife">
<null/>
</property>
<!--第八种:Properties:属性类,键值对-->
<property name="info">
<props>
<prop key="sno">0104180128</prop>
<prop key="sex">男</prop>
<prop key="username">admin</prop>
<prop key="password">123456</prop>
</props>
</property>
</bean>
</beans>
2.编写MyTest测试类
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.toString());
}
}
3.测试结果
结果:查询学生的全部信息!
具体内容如下:
Student{
name=‘张楚岚’,
address=Address{address=‘北京’},
books=[《西游记》, 《三国演义》, 《水浒传》, 《红楼梦》],
hobbies=[听音乐, 看电影, 敲代码],
card={
身份证=410221199908068564,
银行卡=651254386506
},
games=[英雄联盟, 绝地求生, 魔兽争霸],
wife=‘null’,
info={
sno=0104180128,
password=123456,
sex=男,
username=admin } }
6.3 c命名空间和p命名空间注入
可以使用p命名空间和c命名空间进行注入
6.3.1 官方解释
6.3.2 编写User实体类
public class User {
private String name;
private int age;
//无参构造方法
public User() {
}
//有参构造方法
public User(String name, int age) {
this.name = name;
this.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;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
6.3.3 编写userbeans.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!--导入xml约束-->
<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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--p命名空间注入,可以直接注入属性的值:property-->
<bean id="user" class="com.kuang.pojo.User" p:name="周杰伦" p:age="21"></bean>
<!--c命名空间注入,通过构造器注入:construct-args 构造器参数-->
<bean id="user2" class="com.kuang.pojo.User" c:age="18" c:name="胡歌"></bean>
</beans>
注意:p命名空间和c命名空间不能直接使用,需要导入xml约束
<!--p命名空间xml约束-->
xmlns:p="http://www.springframework.org/schema/p"
<!--c命名空间xml约束-->
xmlns:c="http://www.springframework.org/schema/c"
6.3.4 单元测试
1.引入junit资源依赖
- 在项目的pom.xml文件中引入junit资源依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!--引入junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
2. 编写MyTest测试类
public class MyTest {
//单元测试
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user2", User.class);//声明了类型就不需要进行强转
System.out.println(user);
}
}
6.3.5 测试结果
1.使用p命名空间注入
2.使用c命名空间注入
6.4 bean的作用域
6.4.1 bean的作用域表
6.4.2 单例模式
Spring默认机制,单线程使用单例模式
1.编写userbeans.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"
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">
<!--记得引入c命名空间的xml约束:
xmlns:c="http://www.springframework.org/schema/c"
c命名空间注入,通过构造器注入:construct-args 构造器参数-->
<bean id="user2" class="com.kuang.pojo.User"
c:age="18" c:name="胡歌" scope="singleton">
</bean>
</beans>
2.编写MyTest测试类
public class MyTest {
//单元测试
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user2", User.class);//声明了类型就不需要进行强转
User user2 = context.getBean("user2", User.class);//获取同一个类两个不同的实例化对象
System.out.println(user==user2);//判断值是否相同
}
}
3.测试结果
结论:输出结果为ture,因此为单例模式
6.4.3 原型模式
每次从容器中get的时候,都会产生一个新对象,多线程使用原型模式
1.编写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">
<bean id="user2" class="com.kuang.pojo.User"
c:age="18" c:name="胡歌" scope="prototype">
</bean>
</beans>
2.编写MyTest测试类
public class MyTest {
//单元测试
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user2", User.class);//声明了类型就不需要进行强转
User user2 = context.getBean("user2", User.class);//获取同一个类两个不同的实例化对象
System.out.println(user.hashCode());//获取各自的hashcode
System.out.println(user2.hashCode());
System.out.println(user==user2);//判断值是否相同
}
}
3.测试结果
结论:输出的hashcode值不相同,输出结果也为false,因此是原型模式
6.4.4 其他模式
其余的request、session、application等,这些只能在web开发中使用到,这里暂时先不解释了,感兴趣的小伙伴可以自己去查阅一下!
好了,今天的有关Spring基础学习之依赖注入的学习就到此结束啦,欢迎小伙伴们积极学习和讨论,喜欢的可以给蜗牛君点个关注,顺便来个一键三连,我们下期见,拜拜啦!
参考视频链接:https://www.bilibili.com/video/BV1WE411d7Dv(【狂神说Java】Spring5最新教程IDEA版通俗易懂)