今天复习一下Java程序员的饭碗——Spring,Spring可以说是现在作为一个Java程序员必会的内容了,我看过的所有招聘信息上都会写着需要精通Spring全家桶,即Spring,SpringBoot,SpringCould等内容,提到Spring,更是基础内容,像IOC、AOP等概念也要熟记于心,没有Spring的基础,我们就更难理解SpringBoot、SpringCould等高级框架。所以今天重新复习一下,顺便将Spring的学习笔记整理一下。
Spring的雏形(前身)是在2002年提出的interface21框架,在2004年3月24日正式发布了Spring1.0版本,他的创始人是Rod Johnson,是一个音乐学博士(这点没有任何用处,仅对我个人有用,因为我也不是学计算机的,可以用来怼面试官)
优点:
Spring是开源的框架
Spring是轻量级的,非入侵式的框架
控制反转(IOC)和面向切面编程(AOP)
支持事务的处理
支持对其他框架的整合
SpringIOC学习
IOC(Inversion of Control)控制反转 是Spring的一个重点,他用于进行对象的创建,我们先学习一下如何在Spring中创建一个对象
1.我们先创建一个Maven项目
2.在POM文件中导入Spring依赖(Spring的使用需要安装多个包,建议直接导入webmvc,需要用到的包就全部会被导入)
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!-- 有需要的同学也可以使用lombok注解使对象属性简单创建,由于有的部分同学可能了解较少,我这里就不使用了-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
3.创建实体类,Spring的IOC就是将对象的创建交给了Spring管理,所以我们要创建一个实体类用于说明IOC的原理
package DTO;
/**
* @author ME
* @date 2022/2/19 22:51
*/
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
4.在src.main.resources目录下添加Spring配置文件(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="person" class="DTO.Person">
<property name="name" value="张三"/>
</bean>
<!-- <bean id="对象的标识" class="src.java下面的类路径">
<property name="属性名" value="属性值"/>
</bean>-->
</beans>
5.在程序中使用Person对象
import DTO.Person;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author ME
* @date 2022/2/19 22:39
*/
public class StartController {
public static void main(String[] args) {
// 使用XML方式配置Bean容器,多个XML使用逗号分开,获取Spring的上下文对象
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
// 从Spring的上下文对象中根据XML文件中的id的值取出对应的对象
Person person = (Person) applicationContext.getBean("person");
// 打印此对象的内容
System.out.println(person.toString());
}
}
上面介绍的是使用Spring调用无参构造方法set属性进行对象创建。
下面介绍使用Spring调用有参构造方法进行对象创建(只记录更改点)
1.在实体类中添加有参构造方法
package DTO;
/**
* @author ME
* @date 2022/2/19 22:51
*/
public class Person {
private String name;
// 有参构造方法,声明有参构造方法后需要显式创建无参构造方法
// 否则无参构造方法将无法使用
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
2-1.修改applicationContext.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">
<!-- name可以指定别名,多个别名时用逗号进行分割,在getBean的时候使用别名一样可以创建Bean-->
<bean id="person" class="DTO.Person" name="per,myPerson">
<!-- 通过属性下标赋值 index为对象内属性索引 value为具体set的值-->
<!-- 如果属性值为对象 则使用ref导入具体的对象(必须也在Spring容器内才可以) ref="对象bean的id"-->
<constructor-arg index="0" value="啥时能挣6000块"/>
</bean>
<!-- <bean id="对象的标识" class="src.java下面的类路径">
<property name="属性名" value="属性值"/>
</bean>-->
</beans>
2-2.修改applicationContext.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="person" class="DTO.Person">
<!-- 通过属性类型赋值 type为对象内属性类型 value为具体set的值-->
<constructor-arg type="java.lang.String" value="啥时能挣6000块"/>
</bean>
<!-- <bean id="对象的标识" class="src.java下面的类路径">
<property name="属性名" value="属性值"/>
</bean>-->
</beans>
2-3.修改applicationContext.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="person" class="DTO.Person">
<!-- 通过属性名称赋值 name为对象内属性名称 value为具体set的值-->
<constructor-arg name="name" value="啥时能挣6000块"/>
</bean>
<!-- <bean id="对象的标识" class="src.java下面的类路径">
<property name="属性名" value="属性值"/>
</bean>-->
</beans>
有的小伙伴是不是有疑问,constructor-arg标签与property标签有什么区别?
区别在于constructor-arg标签是使用有参构造方法,向里面放值
而property是使用无参构造方法创建对象后,调用set方法向属性内放入值。
以上为SpringIOC进行对象创建的全部方法
如果项目中有多个applicationContext配置文件的时候我们可以使用import标签将配置文件合并
1.创建多个XML配置文件
2.获取配置文件的上下文对象
3.合并配置文件
<?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">
<import resource="beans.xml"/>
</beans>
这种情况适合多人开发防止文件冲突,每个人一个配置文件,或者每个需求一个配置文件就减少了冲突的问题。
如果我们创建的对象中存在依赖关系的时候应该如何创建bean呢?
1.创建动作类—吃的动作
package DTO;
/**
* @author ME
* @date 2022/2/20 9:47
*/
public class Eat {
private String active;
public Eat() {
System.out.println("Eat对象被创建了");
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
@Override
public String toString() {
return "Eat{" +
"active='" + active + '\'' +
'}';
}
}
2.创建角色类—人的角色,放入动作属性
package DTO;
/**
* @author ME
* @date 2022/2/19 22:51
*/
public class Person {
private Eat eat;
public Person() {
System.out.println("Person对象被创建了");
}
public Eat getEat() {
return eat;
}
public void setEat(Eat eat) {
this.eat = eat;
}
@Override
public String toString() {
return "Person{" +
"eat=" + eat +
'}';
}
}
3.在配置文件中配置两个类的关系
<?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="person" class="DTO.Person">
<!-- name表示Person类中的属性名称,ref表示获取Bean容器的ID-->
<property name="eat" ref="eat"/>
</bean>
<!--Person类中只能获取同样在Bean容器内的对象,所以Eat类也需要声明-->
<bean id="eat" class="DTO.Eat">
<property name="active" value="慢慢吃"/>
</bean>
</beans>
4.进行Person对象的创建
import DTO.Person;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author ME
* @date 2022/2/19 22:39
*/
public class StartController {
public static void main(String[] args) {
// 使用XML方式配置Bean容器,多个XML使用逗号分开,获取Spring的上下文对象
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
}
}
5.打印结果
Eat对象就被注入到了Person对象中
SpringIOC创建对象的特点:
1.在程序开始的时候对象就被创建了放在IOC容器内,我们可以使用如下方式进行懒加载(什么时候用什么时候创建)
<!--lazy-init 表示等到使用的时候再进行创建,默认为false-->
<bean id="person" class="DTO.Person" lazy-init="true">
<constructor-arg name="name" value="啥时能挣6000块"/>
</bean>
2.被Spring创建的对象全部为单例模式,我们不管通过getBean()方法获取几次对象,Spring都不会创建新的对象,使用的还是同一个对象。
我们可以使用如下配置进行单例模式或多例模式的选择
<!--scope 表示该对象创建为单例模式还是多例模式 默认为singleton(单例模式) 多例模式为(prototype)-->
<bean id="person" class="DTO.Person" scope="prototype">
<constructor-arg name="name" value="啥时能挣6000块"/>
</bean>
如果不太懂什么是单例模式我这里也有文章进行解释,有需要的同学可以看一下↓
了解完IOC我们来对比一下,之前我们创建对象的方式
import DTO.Person;
/**
* @author ME
* @date 2022/2/19 22:39
*/
public class StartController {
public static void main(String[] args) {
// 无对象依赖的创建
Person person = new Person();
System.out.println(person);
// 有对象依赖的创建
Person person = new Person();
Eat eat = new Eat();
eat.setActive("慢慢吃");
person.setEat(eat);
System.out.println(person);
}
}
DI(Dependency Injection)依赖注入
依赖:Bean对象的创建依赖于IOC容器
注入:Bean对象中的所有属性由IOC容器进行注入
说白了就是给对象的属性赋值的一个过程就是注入。
Spring的注入方式一共有两种:
1.构造器注入
2.Set方法注入
上面简单介绍了使用构造器注入的方式,我这里根据学习的视频课程也只介绍一下Set方式的多类型参数注入,如果有其他的问题可以私聊联系。
1.创建一个复杂的实体类
package DTO;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* @author ME
* @date 2022/2/20 12:16
*/
public class Student {
// 姓名
private String name;
// 地址
private Address address;
// 书籍
private String[] books;
// 爱好
private List<String> hobbys;
// 卡信息
private Map<String, String> carMessage;
// 游戏
private Set<String> games;
// 老婆
private String wife;
// 其他信息
private Properties info;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address +
", books=" + Arrays.toString(books) +
", hobbys=" + hobbys +
", carMessage=" + carMessage +
", 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[] getBooks() {
return books;
}
public void setBooks(String[] books) {
this.books = books;
}
public List<String> getHobbys() {
return hobbys;
}
public void setHobbys(List<String> hobbys) {
this.hobbys = hobbys;
}
public Map<String, String> getCarMessage() {
return carMessage;
}
public void setCarMessage(Map<String, String> carMessage) {
this.carMessage = carMessage;
}
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;
}
}
2.创建一个简单的实体类
package DTO;
/**
* @author ME
* @date 2022/2/20 12:16
*/
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 + '\'' +
'}';
}
}
3.编写applicationContext.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="address" class="DTO.Address">
<property name="address" value="青岛市"/>
</bean>
<bean id="student" class="DTO.Student">
<!-- private String name 姓名-->
<property name="name" value="野原新之助"/>
<!-- private Address address 地址-->
<property name="address" ref="address"/>
<!-- private String[] books 书籍-->
<property name="books">
<array>
<value>哈姆雷特</value>
<value>悲惨世界</value>
<value>百年孤独</value>
</array>
</property>
<!-- private List<String> hobbys 爱好-->
<property name="hobbys">
<list>
<value>写代码</value>
<value>看书</value>
<value>玩游戏</value>
</list>
</property>
<!-- private Map<String, String> carMessage 卡信息-->
<property name="carMessage">
<map>
<entry key="身份证" value="220221199809190000"/>
<entry key="银行卡" value="6210100198989808983291"/>
</map>
</property>
<!-- private Set<String> games 游戏-->
<property name="games">
<set>
<value>辐射避难所</value>
<value>地下城与勇士</value>
</set>
</property>
<!-- private String wife 老婆-->
<property name="wife">
<null/>
</property>
<!-- private Properties info 其他信息-->
<property name="info">
<props>
<prop key="性别">男</prop>
<prop key="小名">蜡笔小新</prop>
</props>
</property>
</bean>
</beans>
4.创建applicationContext上下文对象调用getBean方法创建Student对象
import DTO.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author ME
* @date 2022/2/19 22:39
*/
public class StartController {
public static void main(String[] args) {
// 使用XML方式配置Bean容器,多个XML使用逗号分开,获取Spring的上下文对象
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) applicationContext.getBean("student");
System.out.println(student.getName());
System.out.println(student.getAddress());
System.out.println(student.getBooks());
System.out.println(student.getCarMessage());
System.out.println(student.getGames());
System.out.println(student.getHobbys());
System.out.println(student.getWife());
System.out.println(student.getInfo());
}
}
打印信息如下
扩展学习
我们不论使用有参构造方法进行对象创建,还是使用无参构造方法进行对象创建,这复杂的标签总是弄的人眼花缭乱,所以我们可以使用命名空间,那么该如何使用呢?
<!-- P命名空间-->
xmlns:p="http://www.springframework.org/schema/p"
<!-- C命名空间-->
xmlns:c="http://www.springframework.org/schema/c"
我们在applicationContext.xml文件中声明这两个命名空间
声明时如果出现该行为红色异常状态,并且您使用的编辑器为IDEA,那么请打开File->Settings->schemas and DtDs 位置
扩展空间简单使用
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
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="address" class="DTO.Address">-->
<!-- <property name="address" value="青岛市"/>-->
<!-- </bean>-->
<!-- p命名空间为等同于property标签,使用方式为p:属性名称='属性值',使用p命名空间必须要有无参构造方法-->
<bean id="address" class="DTO.Address" p:address="青岛市"/>
<!-- c命名空间等同于construct-arg标签,使用方式为c:属性名称='属性值',使用c命名空间必须要有有参构造方法-->
<bean id="address" class="DTO.Address" c:address="青岛市"/>
</beans>
对象属性自动装配
在我们上述例子中学生匹配地址的情况我们是这么写的
<?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="sutdent" class="DTO.Student">
<property name="address" ref="address"/>
</bean>
<!-- 子对象创建-->
<bean id="address" class="DTO.Address">
<property name="address" value="青岛市"/>
</bean>
</beans>
那么在自动装配的情况下我们可以使用如下属性
<?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">
<!-- 引入子对象 byName:在容器内寻找与student类属性名相同的bean的id,找到后自动装配-->
<!-- byType:在容器内寻找与student类属性类型相同的bean,找到后自动装配-->
<bean id="student" class="DTO.Student" autowire="byName">
</bean>
<!-- 子对象创建-->
<bean id="address" class="DTO.Address">
<property name="address" value="青岛市"/>
</bean>
</beans>
使用注解进行自动装配
1.在xml文件中添加context地址,然后配置开启注解的标签
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 开启注解的支持-->
<context:annotation-config/>
<bean id="student" class="DTO.Student" />
<bean id="address" class="DTO.Address"/>
</beans>
2.在对象中注入即可使用
@Autowired
private Address address;
Autowired注解先是通过byName的方式匹配,匹配不到再根据byType的方式匹配,当我们没有对应名称的bean,并且有多个对应类型的bean的时候我们可以通过@Qualifier(value="xxx")去指定bean的名称进行注入。
在Java的J2EE中同样有一个注解用来进行自动装配—@Resource注解
这个注解与Autowired的区别在于:
复杂情况下Autowired会在编译时报错,而Resource则是在程序运行期间报错,所以推荐还是Autowired注解(毕竟谁也不想等程序启动之后才发现有问题),两个注解的关于byName还是byType众说纷纭,而我进行尝试了以后发现结论:
两者都是先进行byName比较,byName找不到后再进行byType比较
全面使用Spring注解(这部分逐渐开启了全注解舍弃XML配置文件模式,重点在于面试时会提问,你常用的Spring注解有哪些)
1.使用注解要注意保证导入了spring-aop的包,同时使用context约束
2.创建配置文件
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 指定要扫描的包,加了此配置后该路径下的注解才会生效-->
<context:component-scan base-package="DTO"/>
<!-- 开启注解的支持-->
<context:annotation-config/>
</beans>
3.在实体类中配置
package DTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
* @author ME
* @date 2022/2/20 15:50
*/
/**
* Component = <bean id="person" class="DTO.Person"/>
* 由于Web开发中一般为Controller,Service,Dao层三层架构,所以有等同于Component的三个其他注解
* Controller层 -> @Controller
* Service层 -> @Service
* Dao层 -> @Repository
* 作用就是用于区分文件类型,无具体意义
*/
/**
* Scope表示该Bean为多例模式(prototype)还是单例模式(singleton),默认单例模式
*/
@Scope("singleton")
@Component
public class Person {
// Value = <property name="name" value="孙悟空"/>
@Value("孙悟空")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
注解与xml对比起来,xml更加万能,可读性比较高,工作时使用一般看公司的习惯。
在Spring4以后可以完全舍弃xml文件,配置通过Java类的方法实现
1.创建Java配置类
package config;
import DTO.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* @author ME
* @date 2022/2/20 16:11
*/
/**
* 这个类也会交给Spring管理从而注册到容器中,因为Configuration也是也给Component
* 但是Configuration表示这是一个配置类,相当于XML配置文件
*/
@Configuration
/**
* ComponentScan = <context:component-scan base-package="DTO"/>
*/
@ComponentScan("DTO")
/**
* 如果有多个配置类需要引入的时候可以使用import注解,参数为配置类的class对象
*/
@Import(JavaConfig1.class)
public class JavaConfig {
// Bean注解相当于Bean标签
// Bean = <bean id="person" class="DTO.Person"/>
// bean的id等同于方法名,class等同于返回值类型
@Bean
public Person person() {
return new Person();
}
}
2.创建applicationContext对象调用getBean方法创建Person对象
import DTO.Person;
import config.JavaConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author ME
* @date 2022/2/19 22:39
*/
public class StartController {
public static void main(String[] args) {
// 使用注解方式配置Bean容器,多个class文件使用逗号分开,获取Spring的上下文对象
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(JavaConfig.class);
// 通过配置类中的方法名调用
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
}
}
好了,IOC的内容就这么多,我认为就是Spring对于对象的管理的内容,如果觉得内容对您有帮助的话可以继续看一下AOP部分及事务部分↓