-

后天要去审 java 代码呢,临时抱佛脚把 spring 过一遍吧

0x01 意义

直接看百度百科

1.低侵入式设计,代码污染极低

2.独立于各种应用服务器,基于Spring框架的应用,可以真正实现Write Once,Run Anywhere的承诺

3.Spring的DI机制降低了业务对象替换的复杂性,提高了组件之间的解耦

4.Spring的AOP支持允许将一些通用任务如安全、事务、日志等进行集中式管理,从而提供了更好的复用

5.Spring的ORM和DAO提供了与第三方持久层框架的良好整合,并简化了底层的数据库访问

6.Spring并不强制应用完全依赖于Spring,开发者可自由选用Spring框架的部分或全部

没学过开发知识得看到这几条一定很懵(学过一不一定看得懂,不管那么多反正它好用我们学就是了(又水了一些字数

==总结一句话:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架!==

0x02 认识

组成

image-20240806214901825

Spring 框架是一个分层架构,由 7 个定义良好的模块组成。Spring 模块构建在核心容器之上,核心容器定义了创建、配置和管理 bean 的方式 .

image-20240806214941130

组成 Spring 框架的每个模块(或组件)都可以单独存在,或者与其他一个或多个模块联合实现。每个模块的功能如下:

  • 核心容器:核心容器提供 Spring 框架的基本功能。核心容器的主要组件是 BeanFactory,它是工厂模式的实现。BeanFactory 使用控制反转(IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开。
  • Spring 上下文:Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企业服务,例如 JNDI、EJB、电子邮件、国际化、校验和调度功能。
  • Spring AOP:通过配置管理特性,Spring AOP 模块直接将面向切面的编程功能 , 集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理任何支持 AOP的对象。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖组件,就可以将声明性事务管理集成到应用程序中。
  • Spring DAO:JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写的异常代码数量(例如打开和关闭连接)。Spring DAO 的面向 JDBC 的异常遵从通用的 DAO 异常层次结构。
  • Spring ORM:Spring 框架插入了若干个 ORM 框架,从而提供了 ORM 的对象关系工具,其中包括 JDO、Hibernate 和 iBatis SQL Map。所有这些都遵从 Spring 的通用事务和 DAO 异常层次结构。
  • Spring Web 模块:Web 上下文模块建立在应用程序上下文模块之上,为基于 Web 的应用程序提供了上下文。所以,Spring 框架支持与 Jakarta Struts 的集成。Web 模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。
  • Spring MVC 框架:MVC 框架是一个全功能的构建 Web 应用程序的 MVC 实现。通过策略接口,MVC 框架变成为高度可配置的,MVC 容纳了大量视图技术,其中包括 JSP、Velocity、Tiles、iText 和 POI。

PS: 直接复制狂神师傅的笔记,太晦涩难懂了,我还是先学会怎么用吧,概念这东西用着用着就理解了。

IoC基础

IoC全称 Inversion of Control,直译为控制反转,Spring 提供的容器又称为 IoC 容器。

我们先来看看以往正常业务的控制流程,DAO 和 Service 层密切合作,以确保应用程序能够高效且可靠地运行

  • DAO 就是处理数据库操作的专家,你不需要关心它怎么和数据库打交道,你只需要告诉它你需要什么数据,它会帮你搞定。

  • Service 就是业务逻辑的管理者,它负责处理你的业务需求,比如用户注册、登录等。Service 会调用 DAO 来获取或保存数据,但它主要关注的是业务逻辑的正确性。

比如有一个用户查询的业务需求

UserDao 接口

1
2
3
public interface UserDao {
void getUser();
}

UserDaoImpl 实现类

1
2
3
4
5
public class UserDaoImpl implements UserDao {
public void getUser() {
System.out.println("默认获取用户数据");
}
}

UserService 业务接口

1
2
3
public interface UserService {
void getUser();
}

UserServiceImpl 业务实现类

1
2
3
4
5
6
7
8
public class UserServiceImpl implements UserService {

private UserDao userDao = new UserDaoImpl();

public void getUser() {
userDao.getUser();
}
}

测试

1
2
3
4
5
6
7
8
public class MyTest {
public static void main(String[] args) {

//用户实际调用的是业务层,dao层他们不需要接触!
UserService userService = new UserServiceImpl();
userService.getUser();
}
}

在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码!如果程序代码量十分大,修改一次的成本代价十分昂贵!

比如用户提了一个需求,想分别用 MySql,SqlServer,Oracle 数据库获取用户数据,那我们呢就需要把Userdao的实现类增加一个

1
2
3
4
5
6
public class UserDaoMySqlImpl implements UserDao {
@Override
public void getUser() {
System.out.println("MySql获取用户数据");
}
}

还要去service实现类里面修改对应的实现

1
2
3
4
5
6
7
public class UserServiceImpl implements UserService {
private UserDao userDao = new UserDaoMySqlImpl();
@Override
public void getUser() {
userDao.getUser();
}
}

当业务变得复杂起来的时候,我们这样既要改数据处理又要改业务处理是很麻烦的一件事,那么如何解决呢?

我们使用一个Set接口实现,已经发生了革命性的变化!

1
2
3
4
5
6
7
8
9
10
11
public class UserServiceImpl implements UserService {
private UserDao userDao;
// 利用set实现
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void getUser() {
userDao.getUser();
}
}
1
2
3
4
5
6
7
8
9
@Test
public void test(){
UserServiceImpl service = new UserServiceImpl();
service.setUserDao( new UserDaoMySqlImpl() );
service.getUser();
//那我们现在又想用Oracle去实现呢
service.setUserDao( new UserDaoOracleImpl() );
service.getUser();
}

之前,程序是主动创建对象!控制权在程序猿手上!使用了set注入后,程序不再具有主动性,而是变成了被动的接收对象!

这种思想,从本质上解决了问题,我们程序猿不用再去管理对象的创建了。系统的耦合性大大降低~,可以更加专注的在业务的实现上!这是IOC的原型!

从服务端主导控制权反转到了客户端,也就是客户端主导权,这就是控制反转IOC的意思

hello spring

上面讲的 IOc 是我们自己实现的,现在来看看 spring 是怎么处理的。

新建一个maven项目,编写实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Hello {
private String str;

public String getStr() {
return str;
}

public void setStr(String str) {
this.str = str;
}

@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}

编写xml配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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 类型();
Hello hello = new Hello();

id = 变量名
class = new的对象
property 相当于给对象中的属性设置一个值!
-->
<bean id="hello" class="com.she11F.Hello">
<property name="str" value="Spring"/>
</bean>
</beans>

测试

1
2
3
4
5
6
7
8
9
10
public class MyTest {
public static void main(String[] args) {
//获取Spring的上下文对象!
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

//我们的对象现在都在Spring中的管理了,我们需要使用,直接去里面取出来就可以!
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}

可以发现我们没有用 new 关键字来创建 Hello 对象,而是由Spring创建的,Hello对象的属性是由Spring容器设置的。

这个过程就叫控制反转:

  • 控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的。

  • 反转:程序本身不创建对象,而变成被动的接收对象。

依赖注入:就是利用set方法来进行注入的。

IOC是一种编程思想,由主动的编程变成被动的接收。

我们用这种方式来实现数据库那个案例

1
2
3
4
5
6
7
8
<bean id="MysqlImpl" class="com.she11F.dao.UserDaoMySqlImpl">

</bean>
<bean id="ServiceImpl" class="com.she11F.service.UserServiceImpl">
<!--注意: 这里的name并不是属性 , 而是set方法后面的那部分 , 首字母小写-->
<!--引用另外一个bean , 不是用value 而是用 ref-->
<property name="userDao" ref="MysqlImpl"></property>
</bean>
1
2
3
4
5
6
7
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl serviceImpl = (UserServiceImpl) context.getBean("ServiceImpl");
serviceImpl.getUser();
}
}

到了现在,我们彻底不用在程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IOC,一句话搞定:对象由Spring来创建,管理,装配!

IOC创建对象方式

通过上面配置 xml 然后 spring 容器直接获取对象我们感受到了 spring 的优越性,但是我不禁要问,为什么呢?为什么能直接获取对象,常言道 “当你感受岁月静好之时,一定有人在替你负重前行”,没错,其实是 spring 在偷偷实例化

通过无参构造方法来创建

User.java

1
2
3
4
5
6
7
8
9
10
11
12
public class User {
private String name;
public User() {
System.out.println("user无参构造方法");
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("name="+ name );
}
}

beans.xml

1
2
3
<bean id="user" class="com.she11F.pojo.User">
<property name="name" value="she11F"></property>
</bean>
  1. 测试类
1
2
3
4
5
6
7
8
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//在执行getBean的时候, user已经创建好了 , 通过无参构造
User user = (User) context.getBean("user");
//调用对象的方法 .
user.show();
}

结果可以发现,在调用show方法之前,User对象已经通过无参构造初始化了!

image-20240808231152961

通过有参构造方法来创建

UserT.java

1
2
3
4
5
6
7
8
9
10
11
12
public class UserT {
private String name;
public UserT(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("name="+ name );
}
}

beans.xml 有三种方式编写

1
2
3
4
5
<!-- 第一种根据index参数下标设置 -->
<bean id="userT" class="com.kuang.pojo.UserT">
<!-- index指构造方法 , 下标从0开始 -->
<constructor-arg index="0" value="she11F"/>
</bean>
1
2
3
4
5
<!-- 第二种根据参数名字设置,最推荐 -->
<bean id="userT" class="com.kuang.pojo.UserT">
<!-- name指参数名 -->
<constructor-arg name="name" value="she11F"/>
</bean>
1
2
3
4
<!-- 第三种根据参数类型设置,不推荐 -->
<bean id="userT" class="com.kuang.pojo.UserT">
<constructor-arg type="java.lang.String" value="she11F"/>
</bean>

结论:在配置文件加载的时候。其中管理的对象都已经初始化了!

Spring配置

别名

alias 设置别名 , 为bean设置别名 , 可以设置多个别名

1
2
<!--设置别名:在获取Bean的时候可以使用别名获取-->
<alias name="userT" alias="userNew"/>
Bean的配置
1
2
3
4
5
6
7
8
9
10
11
<!--bean就是java对象,由Spring创建和管理-->
<!--
id 是bean的标识符,要唯一,如果没有配置id,name就是默认标识符
如果配置id,又配置了name,那么name是别名
name可以设置多个别名,可以用逗号,分号,空格隔开
如果不配置id和name,可以根据applicationContext.getBean(.class)获取对象;
class是bean的全限定名=包名+类名
-->
<bean id="hello" name="hello2 h2,h3;h4" class="com.kuang.pojo.Hello">
<property name="name" value="Spring"/>
</bean>
import

团队的合作通过import来实现 .

1
<import resource="{path}/beans.xml"/>

依赖注入(DI)

  • 依赖注入(Dependency Injection,DI)。
  • 依赖 : 指 Bean 对象的创建依赖于容器 . Bean对象的依赖资源 .
  • 注入 : 指 Bean 对象所依赖的资源 , 由容器来设置和装配 .
构造器注入

前面的案例有

set注入 (重点)

要求被注入的属性 , 必须有set方法 , set方法的方法名由set + 属性首字母大写 , 如果属性是boolean类型 , 没有set方法 , 是 is .

测试pojo类 :

Address.java

1
2
3
4
5
6
7
8
9
10
11
package com.she11F.pojo;

public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

Student

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.she11F.pojo;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
public void setName(String name) {
this.name = name;
}
public void setAddress(Address address) {
this.address = address;
}
public void setBooks(String[] books) {
this.books = books;
}
public void setHobbys(List<String> hobbys) {
this.hobbys = hobbys;
}
public void setCard(Map<String, String> card) {
this.card = card;
}
public void setGames(Set<String> games) {
this.games = games;
}
public void setWife(String wife) {
this.wife = wife;
}
public void setInfo(Properties info) {
this.info = info;
}
public String getName() {
return name;
}
public void show(){
System.out.println("name="+ name
+ ",address="+ address.getAddress()
+ ",books="
);
for (String book:books){
System.out.print("<<"+book+">>\t");
}
System.out.println("\n爱好:"+hobbys);
System.out.println("card:"+card);
System.out.println("games:"+games);
System.out.println("wife:"+wife);
System.out.println("info:"+info);
}
}
  1. 常量注入

    1
    2
    3
    <bean id="student" class="com.kuang.pojo.Student">
    <property name="name" value="小明"/>
    </bean>
  2. Bean注入

    ==注意点:这里的值是一个引用,ref==

    1
    <property name="address" ref="addr"/>
  3. 数组注入

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <bean id="student" class="com.she11F.pojo.Student">
    <property name="name" value="小明"/>
    <property name="address" ref="addr"/>
    <property name="books">
    <array>
    <value>西游记</value>
    <value>红楼梦</value>
    <value>水浒传</value>
    </array>
    </property>
    </bean>
  4. List注入

    1
    2
    3
    4
    5
    6
    7
    <property name="hobbys">
    <list>
    <value>听歌</value>
    <value>看电影</value>
    <value>爬山</value>
    </list>
    </property>
  5. Map注入

    1
    2
    3
    4
    5
    6
    <property name="card">
    <map>
    <entry key="中国邮政" value="456456456465456"/>
    <entry key="建设" value="1456682255511"/>
    </map>
    </property>
  6. set注入

    1
    2
    3
    4
    5
    6
    7
    <property name="games">
    <set>
    <value>LOL</value>
    <value>BOB</value>
    <value>COC</value>
    </set>
    </property>
  7. Null注入

    1
    <property name="wife"><null/></property>
  8. Properties注入

    1
    2
    3
    4
    5
    6
    7
    <property name="info">
    <props>
    <prop key="学号">20190604</prop>
    <prop key="性别">男</prop>
    <prop key="姓名">小明</prop>
    </props>
    </property>

    跑出结果如图所示

    image-20240809203650565

拓展注入实现

User.java : 【注意:这里没有有参构造器!】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class User {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

1、P命名空间注入 : 需要在头文件中加入约束文件

1
2
3
导入约束 : xmlns:p="http://www.springframework.org/schema/p"
<!--P(属性: properties)命名空间 , 属性依然要设置set方法-->
<bean id="user" class="com.she11F.pojo.User" p:name="she11f" />

2、c 命名空间注入 : 需要在头文件中加入约束文件

1
2
3
导入约束 : xmlns:c="http://www.springframework.org/schema/c"
<!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
<bean id="user" class="com.kuang.pojo.User" c:name="she11f" c:age="18"/>

发现问题:爆红了,刚才我们没有写有参构造!

解决:把有参构造器加上,这里也能知道,c 就是所谓的构造器注入!

Bean的作用域

在Spring中,那些组成应用程序的主体及由Spring IoC容器所管理的对象,被称之为bean。简单地讲,bean就是由IoC容器初始化、装配及管理的对象 .

image-20240810233156403

几种作用域中,request、session作用域仅在基于web的应用中使用(不必关心你所采用的是什么web应用框架),只能用在基于web的Spring ApplicationContext环境。

Singleton

当一个bean的作用域为Singleton,那么Spring IoC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。Singleton是单例类型,就是在创建起容器时就同时自动创建了一个bean的对象,不管你是否使用,他都存在了,每次获取到的对象都是同一个对象。注意,Singleton作用域是Spring中的缺省作用域。要在XML中将bean定义成singleton,可以这样配置:

1
<bean id="user" class="com.she11F.pojo.User" c:name="she11f" c:age="20" scope="singleton"/>

测试:

1
2
3
User user1 = (User) context.getBean("user");
User user2 = (User) context.getBean("user");
System.out.println(user1 == user2);

返回 true

Prototype

当一个bean的作用域为Prototype,表示一个bean定义对应多个对象实例。Prototype作用域的bean会导致在每次对该bean请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)时都会创建一个新的bean实例。Prototype是原型类型,它在我们创建容器的时候并没有实例化,而是当我们获取bean的时候才会去创建一个对象,而且我们每次获取到的对象都不是同一个对象。根据经验,对有状态的bean应该使用prototype作用域,而对无状态的bean则应该使用singleton作用域。在XML中将bean定义成prototype,可以这样配置:

1
2
3
scope="prototype"
或者
singleton="false"

Request

当一个bean的作用域为Request,表示在一次HTTP请求中,一个bean定义对应一个实例;即每个HTTP请求都会有各自的bean实例,它们依据某个bean定义创建而成。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:

1
scope="request"

针对每次HTTP请求,Spring容器会根据loginAction bean的定义创建一个全新的LoginAction bean实例,且该loginAction bean实例仅在当前HTTP request内有效,因此可以根据需要放心的更改所建实例的内部状态,而其他请求中根据loginAction bean定义创建的实例,将不会看到这些特定于某个请求的状态变化。当处理请求结束,request作用域的bean实例将被销毁。

Session

当一个bean的作用域为Session,表示在一个HTTP Session中,一个bean定义对应一个实例。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:

1
scope="session"

针对某个HTTP Session,Spring容器会根据userPreferences bean定义创建一个全新的userPreferences bean实例,且该userPreferences bean仅在当前HTTP Session内有效。与request作用域一样,可以根据需要放心的更改所创建实例的内部状态,而别的HTTP Session中根据userPreferences创建的实例,将不会看到这些特定于某个HTTP Session的状态变化。当HTTP Session最终被废弃的时候,在该HTTP Session作用域内的bean也会被废弃掉。

Bean的自动装配

  • 自动装配是使用spring满足bean依赖的一种方法
  • spring会在应用上下文中为某个bean寻找其依赖的bean。

Spring中bean有三种装配机制,分别是:

  1. 在xml中显式配置;
  2. 在java中显式配置;
  3. 隐式的bean发现机制和自动装配。

这里我们主要讲第三种:自动化的装配bean。

Spring的自动装配需要从两个角度来实现,或者说是两个操作:

  1. 组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean;
  2. 自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IoC/DI;

组件扫描和自动装配组合发挥巨大威力,使的显示的配置降低到最少。

测试环境搭建

新建两个实体类,Cat Dog 都有一个叫的方法

1
2
3
4
5
public class Cat {
public void shout() {
System.out.println("miao~");
}
}
1
2
3
4
5
public class Dog {
public void shout() {
System.out.println("wang~");
}
}

新建一个用户类 User

1
2
3
4
5
public class User {
private Cat cat;
private Dog dog;
private String str;
}

编写Spring配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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="dog" class="com.she11F.pojo.Dog"/>
<bean id="cat" class="com.she11F.pojo.Cat"/>
<bean id="user" class="com.she11F.pojo.User">
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
<property name="str" value="qinjiang"/>
</bean>
</beans>

正常的 xml 注入我们就不讲了,看看自动化装配

byName

autowire byName (按名称自动装配)

1
2
3
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean id!
-->

由于在手动配置xml过程中,常常发生字母缺漏和大小写等错误,而无法对其进行检查,使得开发效率降低。

采用自动装配将避免这些错误,并且使配置简单化。

测试:

  1. 修改bean配置,增加一个属性 autowire=”byName”
1
2
3
<bean id="user" class="com.she11f.pojo.User" autowire="byName">
<property name="str" value="she11f"/>
</bean>
1
2
3
4
5
6
7
8
9
10
11
<?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="dog" class="com.she11F.pojo.Dog"/>
<bean id="cat" class="com.she11F.pojo.Cat"/>
<bean id="user" class="com.she11F.pojo.User" autowire="byName">
<property name="str" value="she11f"/>
</bean>
</beans>
  1. 再次测试,结果依旧成功输出!
  2. 我们将 cat 的bean id修改为 catXXX
  3. 再次测试, 执行时报空指针java.lang.NullPointerException。因为按byName规则找不对应set方法,真正的setCat就没执行,对象就没有初始化,所以调用时就会报空指针错误。

小结:

当一个bean节点带有 autowire byName的属性时。

  1. 将查找其类中所有的set方法名,例如setCat,获得将set去掉并且首字母小写的字符串,即cat。
  2. 去spring容器中寻找是否有此字符串名称id的对象。
  3. 如果有,就取出注入;如果没有,就报空指针异常。
byType

autowire byType (按类型自动装配)

1
2
3
<!--
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean!
-->

使用autowire byType首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。

1
NoUniqueBeanDefinitionException

测试:

  1. 将user的bean配置修改一下 : autowire="byType"
  2. 测试,正常输出
  3. 再注册一个cat 的bean对象!
  4. 测试,报错:NoUniqueBeanDefinitionException
  5. 删掉cat2,将cat的bean名称改掉!测试!因为是按类型装配,所以并不会报异常,也不影响最后的结果。甚至将id属性去掉,也不影响结果。

这就是按照类型自动装配!

使用注解

dk1.5开始支持注解,spring2.5开始全面支持注解。

准备工作: 利用注解的方式注入属性。

在spring配置文件中引入context文件头

1
2
3
4
5
6
7
8
9
10
11
12
<?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/>
</beans>

@Autowired

  • @Autowired是按类型自动转配的,不支持id匹配。
  • 需要导入 spring-aop的包!

测试:

  1. 将User类中的set方法去掉,使用@Autowired注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class User {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String str;
public Cat getCat() {
return cat;
}
public Dog getDog() {
return dog;
}
public String getStr() {
return str;
}
}

@Autowired(required=false) 说明: false,对象可以为null;true,对象必须存对象,不能为null。

1
2
3
//如果允许对象为null,设置required = false,默认为true
@Autowired(required = false)
private Cat cat;

@Qualifier

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value = “xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入!

测试实验步骤:

  1. 配置文件修改内容,保证类型存在对象。且名字不为类的默认名字!

    1
    2
    3
    4
    5
    6
    7
    <bean id="dog1" class="com.she11F.pojo.Dog"/>
    <bean id="dog2" class="com.she11F.pojo.Dog"/>
    <bean id="cat1" class="com.she11F.pojo.Cat"/>
    <bean id="cat2" class="com.she11F.pojo.Cat"/>
    <bean id="user" class="com.she11F.pojo.User" >
    <property name="str" value="she11f"/>
    </bean>
  2. 没有加Qualifier测试,直接报错

  3. 在属性上添加Qualifier注解

1
2
3
4
5
6
@Autowired
@Qualifier(value = "cat2")
private Cat cat;
@Autowired
@Qualifier(value = "dog2")
private Dog dog;

@Resource

  • @Resource如有指定的name属性,先按该属性进行byName方式查找装配;
  • 其次再进行默认的byName方式进行装配;
  • 如果以上都不成功,则按byType的方式自动装配。
  • 都不成功,则报异常。

实体类:

1
2
3
4
5
6
7
8
public class User {
//如果允许对象为null,设置required = false,默认为true
@Resource(name = "cat2")
private Cat cat;
@Resource
private Dog dog;
private String str;
}
1
2
3
4
<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>
<bean id="cat2" class="com.kuang.pojo.Cat"/>
<bean id="user" class="com.kuang.pojo.User"/>

测试:结果OK

配置文件2:beans.xml , 删掉cat2

1
2
<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>

实体类上只保留注解

1
2
3
4
@Resource
private Cat cat;
@Resource
private Dog dog;

结果:OK

结论:先进行byName查找,失败;再进行byType查找,成功。

@Autowired@Resource异同:

  1. @Autowired@Resource都可以用来装配bean。都可以写在字段上,或写在setter方法上。
  2. @Autowired默认按类型装配(属于spring规范),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用
  3. @Resource(属于J2EE复返),默认按照名称进行装配,名称可以通过name属性进行指定。如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。 当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。

它们的作用相同都是用注解方式注入对象,但执行顺序不同。@Autowired先byType,@Resource先byName。

使用注解开发

在spring4之后,想要使用注解形式,必须得要引入aop的包

使用注解需要导入约束,配置注解的支持!

1
2
3
4
5
6
7
8
9
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
Bean的实现

我们之前都是使用 bean 的标签进行bean注入,但是实际开发中,我们一般都会使用注解!

  1. 配置扫描哪些包下的注解
1
2
<!--指定注解扫描包-->
<context:component-scan base-package="com.she11F.pojo"/>

在指定包下编写类,增加注解

1
2
3
4
5
@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
public String name = "she11F";
}
属性注入

使用注解注入属性

  1. 可以不用提供set方法,直接在直接名上添加@value(“值”)
1
2
3
4
5
6
7
@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
@Value("she11F")
// 相当于配置文件中 <property name="name" value="she11F"/>
public String name;
}
衍生注解

我们这些注解,就是替代了在配置文件当中配置步骤而已!更加的方便快捷!

@Component三个衍生注解

为了更好的进行分层,Spring可以使用其它三个注解,功能一样,目前使用哪一个功能都一样。

写上这些注解,就相当于将这个类交给Spring管理装配了!

自动装配注解

在Bean的自动装配已经讲过了,可以回顾!

作用域

@scope

  • singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。
  • prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收
1
2
3
4
5
6
@Controller("user")
@Scope("prototype")
public class User {
@Value("she11F")
public String name;
}

XML与注解比较

  • XML可以适用任何场景 ,结构清晰,维护方便
  • 注解不是自己提供的类使用不了,开发简单方便

xml与注解整合开发 :推荐最佳实践

  • xml管理Bean
  • 注解完成属性注入
  • 使用过程中, 可以不用扫描,扫描是为了类上的注解
1
<context:annotation-config/>

作用:

  • 进行注解驱动注册,从而使注解生效
  • 用于激活那些已经在spring容器里注册过的bean上面的注解,也就是显示的向Spring注册
  • 如果不扫描包,就需要手动配置bean
  • 如果不加注解驱动,则注入的值为null!
基于 Java 类进行配置 Spring

JavaConfig 原来是 Spring 的一个子项目,它通过 Java 类的方式提供 Bean 的定义信息,在 Spring4 的版本, JavaConfig 已正式成为 Spring4 的核心功能 。

1
2
3
4
5
@Component  //将这个类标注为Spring的一个组件,放到容器中!
public class User {
@Value("she11F")
public String name;
}

这里 @Component 这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中

新建一个 config 配置包,编写一个MyConfig配置类

1
2
3
4
5
6
7
@Configuration  //代表这是一个配置类
public class MyConfig {
@Bean //通过方法注册一个bean,这里的返回值就Bean的类型,方法名就是bean的id!
public User user(){
return new User();
}
}

测试类

1
2
3
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = (User) context.getBean("user");
System.out.println(user.name);

导入其他配置如何做呢?

  1. 我们再编写一个配置类!

    1
    2
    3
    @Configuration  //代表这是一个配置类
    public class MyConfig2 {
    }
  2. 在之前的配置类中我们来选择导入这个配置类

    1
    2
    3
    4
    5
    6
    7
    8
    @Configuration
    @Import(MyConfig2.class) //导入合并其他配置类,类似于配置文件中的 inculde 标签
    public class MyConfig {
    @Bean
    public Dog dog(){
    return new Dog();
    }
    }

关于这种Java类的配置方式,我们在之后的SpringBoot 和 SpringCloud中还会大量看到,我们需要知道这些注解的作用即可!

AOP

AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

image-20240813193231750

Aop在Spring中的作用

==提供声明式事务;允许用户自定义切面==

  • 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 ….
  • 切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
  • 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
  • 目标(Target):被通知对象。
  • 代理(Proxy):向目标对象应用通知之后创建的对象。
  • 切入点(PointCut):切面通知 执行的 “地点”的定义。
  • 连接点(JointPoint):与切入点匹配的执行点。

image-20240813193424161

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:

image-20240813193647889

即 Aop 在 不改变原有代码的情况下 , 去增加新的功能 .

通过 Spring API 实现

【重点】使用AOP织入,需要导入一个依赖包!

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>

第一种方式

通过 Spring API 实现

首先编写我们的业务接口和实现类

1
2
3
4
5
6
public interface UserService {
public void add();
public void delete();
public void update();
public void search();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加用户");
}
@Override
public void delete() {
System.out.println("删除用户");
}
@Override
public void update() {
System.out.println("更新用户");
}
@Override
public void search() {
System.out.println("查询用户");
}
}

然后去写我们的增强类 , 我们编写两个 , 一个前置增强 一个后置增强

1
2
3
4
5
6
7
8
9
public class Log implements MethodBeforeAdvice {
//method : 要执行的目标对象的方法
//objects : 被调用的方法的参数
//Object : 目标对象
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println( o.getClass().getName() + "的" + method.getName() + "方法被执行了");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
public class AfterLog implements AfterReturningAdvice {
//returnValue 返回值
//method被调用的方法
//args 被调用的方法的对象的参数
//target 被调用的目标对象
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了" + target.getClass().getName()
+"的"+method.getName()+"方法,"
+"返回值:"+returnValue);
}
}

最后去spring的文件中注册 , 并实现aop切入实现 , 注意导入约束 .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.she11F.service.UserServiceImpl"/>
<bean id="log" class="com.she11F.log.Log"/>
<bean id="afterLog" class="com.she11F.log.AfterLog"/>
<!--aop的配置-->
<aop:config>
<!--切入点 expression:表达式匹配要执行的方法-->
<aop:pointcut id="pointcut" expression="execution(* com.she11F.service.UserServiceImpl.*(..))"/>
<!--执行环绕; advice-ref执行方法 . pointcut-ref切入点-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>

image-20240813195326432

第二种方式

自定义类来实现Aop

目标业务类不变依旧是userServiceImpl

第一步 : 写我们自己的一个切入类

1
2
3
4
5
6
7
8
public class DiyPointcut {
public void before(){
System.out.println("---------方法执行前---------");
}
public void after(){
System.out.println("---------方法执行后---------");
}
}

去spring中配置

1
2
3
4
5
6
7
8
9
10
11
12
13
<!--第二种方式自定义实现-->
<!--注册bean-->
<bean id="diy" class="com.she11F.diy.DiyPointcut"/>
<bean id="userService" class="com.she11F.service.UserServiceImpl"/>
<!--aop的配置-->
<aop:config>
<!--第二种方式:使用AOP的标签实现-->
<aop:aspect ref="diy">
<aop:pointcut id="diyPonitcut" expression="execution(* com.she11F.service.UserServiceImpl.*(..))"/>
<aop:before pointcut-ref="diyPonitcut" method="before"/>
<aop:after pointcut-ref="diyPonitcut" method="after"/>
</aop:aspect>
</aop:config>

第三种方式

使用注解实现

第一步:编写一个注解实现的增强类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.she11F.diy;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class AnnotationPointcut {
@Before("execution(* com.she11F.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("---------方法执行前---------");
}
@After("execution(* com.she11F.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("---------方法执行后---------");
}
@Around("execution(* com.she11F.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
System.out.println("签名:"+jp.getSignature());
//执行目标方法proceed
Object proceed = jp.proceed();
System.out.println("环绕后");
System.out.println(proceed);
}
}

第二步:在Spring配置文件中,注册bean,并增加支持注解的配置

1
2
3
<!--第三种方式:注解实现-->
<bean id="annotationPointcut" class="com.kuang.config.AnnotationPointcut"/>
<aop:aspectj-autoproxy/>

aop:aspectj-autoproxy:说明

1
通过aop命名空间的<aop:aspectj-autoproxy />声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面。当然,spring 在内部依旧采用AnnotationAwareAspectJAutoProxyCreator进行自动代理的创建工作,但具体实现的细节已经被<aop:aspectj-autoproxy />隐藏起来了 <aop:aspectj-autoproxy />有一个proxy-target-class属性,默认为false,表示使用jdk动态代理织入增强,当配为<aop:aspectj-autoproxy  poxy-target-class="true"/>时,表示使用CGLib动态代理技术织入增强。不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。

整合Mybatis

步骤:

  1. 导入相关jar包

    • junit

      1
      2
      3
      4
      5
      <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      </dependency>
    • mybatis

      1
      2
      3
      4
      5
      <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.2</version>
      </dependency>
    • mysql数据库

      1
      2
      3
      4
      5
      <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
      </dependency>
    • spring相关

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.10.RELEASE</version>
      </dependency>
      <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.10.RELEASE</version>
      </dependency>
    • aop织入器

      1
      2
      3
      4
      5
      6
      <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
      <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.4</version>
      </dependency>
    • mybatis-spring整合包【重点】在此还导入了lombok包。

      1
      2
      3
      4
      5
      <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.2</version>
      </dependency>
    • 配置Maven静态资源过滤问题!

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      <build>
      <resources>
      <resource>
      <directory>src/main/java</directory>
      <includes>
      <include>**/*.properties</include>
      <include>**/*.xml</include>
      </includes>
      <filtering>true</filtering>
      </resource>
      </resources>
      </build>
  2. 编写配置文件

  3. 测试

回忆MyBatis

配置 pojo

1
2
3
4
5
public class User {
private int id; //id
private String name; //姓名
private String pwd; //密码
}

实现mybatis的配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.she11F.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.she11F.dao"/>
</mappers>
</configuration>

编写UserMapper接口

1
2
3
public interface UserMapper {
public List<User> selectUser();
}

编写UserMapper.xml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.kuang.mapper.UserMapper">

<!--sql-->
<select id="selectUser" resultType="user">
select * from mybatis.user
</select>
</mapper>

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
public void selectUser() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.selectUser();
for (User user: userList){
System.out.println(user);
}
sqlSession.close();
}

先写到这里吧,先去看 SpringMVC ,Spring 整合 MyBatis 之后重新创建一个项目来看