Spring框架学习笔记:从IoC到声明式事务

1 阅读18分钟

1、Spring

1.1、简介

  • Spring:春天------> 给软件行业带来了春天!

  • 2002,首次推出了Spring框架的雏形:interface21框架!

  • Spring框架即以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日,发布了1.0正式版。

  • Rod Johnson,Spring Framework创始人,著名作者。很难想象Rod Johnson的学历,真的让好多人大吃一惊,他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。

  • spring理念:使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架!

  • SSH : Struct2 + Spring + Hibernate!

  • SSM : SpringMvc + Spring + Mybatis!

  • 官网:spring.io/projects/sp…

  • 官方下载地址:repo.spring.io/release/org…

  • GitHub:github.com/spring-proj…

<!-- Source: https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>7.0.6</version>
    <scope>compile</scope>
</dependency>
<!-- Source: https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>7.0.6</version>
    <scope>compile</scope>
</dependency>

1.2、优点

  • Spring是一个开源的免费的框架(容器)!
  • Spring是一个轻量级的、非入侵式的框架!
  • 控制反转(IOC),面向切面编程(AOP)!
  • 支持事务的处理,对框架整合的支持!

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

1.3、组成

image.png

2、IOC理论

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

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

private UserDao userDao;

//利用set进行动态实现值的注入!
public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
}
  • 之前,程序是主动创建对象!控制权在程序猿手上!
  • 使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象!

1. 以前的写法(耦合死)

运行

public class UserService {
    // 写死了!只能用 UserDaoMysqlImpl
    private UserDao userDao = new UserDaoMysqlImpl();
}

这种:

  • 你想换成 UserDaoOracleImpl
  • 必须改这行代码
  • 必须重新编译 class
  • 必须重新打包部署

因为你把实现类写死在代码里了。


2. 现在的写法(解耦)

运行

public class UserService {
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}

重点来了:

UserService 从头到尾,不知道、也不关心 userDao 具体是谁实现的!

它只知道:

你给我一个 UserDao 接口的实现,我就用。


3. 那要换实现,改哪里?

不是改 UserService,而是改 “谁调用 UserService、谁给它 set 对象” 的地方!

比如以前是:

UserService service = new UserService();
service.setUserDao(new UserDaoMysqlImpl()); // 用 MySQL

现在要换成 Oracle,只改这里:

service.setUserDao(new UserDaoOracleImpl()); // 换成 Oracle

UserService 这个业务类,一行没动!

业务逻辑完全没改!不需要重新编译 UserService!

IOC本质

控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。没有IoC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,DI)。

3、HelloSpring

  • 首先编写一个标准的实体类,Spring称其为Bean类
package com.zhang.pojo;

public class Hello {
    private String str;

    public String getStr() {
        return str;
    }

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

    public Hello(String str) {
        this.str = str;
    }

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

    public Hello() {
    }
}
  • 编写Spring Bean 配置文件,告诉 Spring 要创建哪些对象,给对象赋什么值,这是 Spring 容器的配置文件
<?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.zhang.pojo.Hello" >
        <property name="str" value="你好 Spring" />
    </bean>


</beans>
  • 编写测试
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
//        获取Spring的上下文对象
        ApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");
//        现在我们的对象就都在Spring容器里管理了,想要直接取出来即可
        Object hello = context.getBean("hello");
        System.out.println(hello);
    }
}

image.png

这个过程就叫控制反转:

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

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

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

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

可以通过new ClassPathXmlApplicationContext去浏览一下底层源码。

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

4、IOC创建对象的方式

  1. 使用无参构造创建对象,默认!

  2. 假设我们要使用有参构造创建对象

  • 下标赋值

    在使用全参构造而不是无参构造时用,index表示第n+1个参数

<bean id="user" class="com.kuang.pojo.User">

<constructor-arg index="0" value="狂神说Java"/>

</bean>
  • 类型

    typle表示参数类型,如果多个参数类型一样就会出问题。因此不建议使用

<bean id="user" class="com.kuang.pojo.User">

<constructor-arg type="java.lang.String" value="qinjiang"/>

</bean>
  • 参数名

    最直观简单的方式

<bean id="user" class="com.kuang.pojo.User">

<constructor-arg name="name" value="秦疆"/>

</bean>

Spring 默认模式下,Bean 容器启动时即一次性创建所有单例对象,且对同一 Bean 的多次获取始终返回同一个实例。

  • spring实际不管你获取的是哪个bean,比如我注册了user和admin两个类,我get出User的时候,admin实例也同时被创建了,而且我get两次user,得到的是同一个user

5、Spring配置

5.1、别名

给bean添加别名

<bean id="hello" class="com.zhang.pojo.Hello" >
    <property name="str" value="你好 Spring" />
</bean>
<alias name="hello" alias="hello2"/>
    public static void main(String[] args) {
//        获取Spring的上下文对象
        ApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");
//        现在我们的对象就都在Spring容器里管理了,想要直接取出来即可
        Object hello = context.getBean("hello2");
        System.out.println(hello);
    }

5.2、Bean的配置

<!--

id:bean 的唯一标识符,也就是相当于我们学的对象名

class:bean 对象所对应的全限定名 : 包名 + 类型

name :也是别名,而且name 可以同时取多个别名,可以用逗号,空格,分号分隔多个别名

-->

<bean id="userT" class="com.kuang.pojo.UserT" name="user2 u2,u3;u4">

<property name="name" value="西部开源"/>

</bean>

5.3、import

这个import,一般用于团队开发使用,他可以将多个配置文件,导入合并为一个

假设,现在项目中有多个人开发,这三个人复制不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的!

  • 张三 beans
  • 李四 beans2
  • 王五 beans3
  • ApplicationContext.xml
<import resource="beans.xml"/>

<import resource="beans2.xml"/>

<import resource="beans3.xml"/>

使用的时候,直接使用总的配置就可以了

ApplicationContext context =
        new ClassPathXmlApplicationContext("ApplicationContext.xml");

6、依赖注入

6.1、构造器注入

前面已经说过了

<bean id="user" class="com.kuang.pojo.User">

<constructor-arg name="name" value="秦疆"/>

</bean>

6.2、Set方式注入

环境搭建

package com.zhang.pojo;

import java.util.*;

public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbies;
    private Map<String, String> cards;
    private Set<String> games;
    private String wife;
    private Properties info;


不同类的注入方式

<bean id="student" class="com.zhang.pojo.Student" >
<!--        普通值注入,用value-->
        <property name="name" value="zhanglei"/>
<!--        对象注入,用ref-->
        <property name="address" ref="adddress"/>
<!--        数组,用array标签-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>三国演义</value>
                <value>西游记</value>
                <value>水浒传</value>
            </array>
<!--            集合,用list标签-->
        </property>
        <property name="hobbies">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
            </list>
        </property>
        <!--Map,用Map标签-->
        <property name="cards">
            <map>
                <entry key="身份证" value="111111222222223333"/>
                <entry key="银行卡" value="1321231312312313123"/>
            </map>
        </property>

        <!--Set,用Set标签-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>

        <!--指定某个元素为时用null标签,为空时用value=“”-->
        <property name="wife">
            <null/>
        </property>

        <!--Properties-->
        <property name="info">
            <props>
                <prop key="学号">20190525</prop>
                <prop key="性别"></prop>
            </props>
        </property>
    </bean>

image.png

6.3、拓展方式注入

p命名空间

作用:简化 setter 注入(对应 <property>本质:用 XML 属性代替 <property> 子标签

使用步骤

  1. 声明命名空间(在 <beans> 根标签)
xmlns:p="http://www.springframework.org/schema/p"
  1. 语法
  • 普通值p:属性名="值"
  • 引用 Beanp:属性名-ref="Bean的id"
  • 要求:类必须有 无参构造 + setter 方法
<?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"
       
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
    <bean id="student2" class="com.zhang.pojo.Student" p:name="zhanglei"/>
 </beans>
import com.zhang.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mytest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
//        这样写可以避免强转
        Student student2 = applicationContext.getBean("student2", Student.class);
        System.out.println(student2.getName());
    }
}

image.png

c命名空间

作用:简化 构造器注入(对应 <constructor-arg>本质:用 XML 属性代替 <constructor-arg> 子标签

使用步骤

  1. 声明命名空间
xmlns:c="http://www.springframework.org/schema/c"
  1. 两种写法
  • 按参数名(推荐):c:参数名="值"c:参数名-ref="id"
  • 按索引(不推荐):c:_0="值", c:_1="值"
  • 要求:类必须有 对应的有参构造方法
c命名空间 = 构造器参数顺序地狱。Spring 7.0+ 推断混乱,类型匹配玄学,报错信息 misleading。有这时间折腾,<constructor-arg> 三行代码稳如老狗。

6.4、Bean的作用域

  1. 单例模式(Spring默认机制 所有get到的对象是一个对象)
 <bean id="user2" class="com.kuang.pojo.User" c:age="18" c:name="狂神"

    scope="singleton"/>
  1. 原型模式:每次从容器中get的时候,都会产生一个新对象!
   <bean id="accountService" class="com.something.DefaultAccountService"

    scope="prototype"/>
  1. 其余的 request、session、application、这些个只能在web开发中使用到!

7、Bean的自动装配

  • 自动装配是Spring满足bean依赖一种方式!
  • Spring会在上下文中自动寻找,并自动给bean装配属性!

在Spring中有三种装配的方式

  1. 在xml中显式的配置
  2. 在java中显式配置
  3. 隐式的自动装配bean

7.1、测试环境

  • 实体类
public class People {
    private String name;
    private Dog dog;
    private Cat cat;

}
public class Cat {
    public void shout(){
        System.out.println("miao");
    }
}
public class Dog {
    public void shout(){
        System.out.println("wang");
    }
}
  • 测试
<?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="people" class="com.zhang.pojo.People">
    <property name="name" value="张磊"/>
    <property name="cat" ref="cat"/>
    <property name="dog" ref="dog"/>
</bean>
    <bean id="cat" class="com.zhang.pojo.Cat"/>
    <bean id="dog" class="com.zhang.pojo.Dog"/>
</beans>

D:\develop-tools\Environment\JDK\jdk-17.0.2\bin\java.exe "-javaagent:D:\develop-tools\IDEA\IntelliJ IDEA 2025.1.1.1\lib\idea_rt.jar=52840" -Dfile.encoding=UTF-8 -classpath D:\code\JAVA\IDEA\SpringStudy\spring03-antowire\target\test-classes;D:\code\JAVA\IDEA\SpringStudy\spring03-antowire\target\classes;D:\develop-tools\Environment\Maven\maven-repository\org\springframework\spring-webmvc\7.0.6\spring-webmvc-7.0.6.jar;D:\develop-tools\Environment\Maven\maven-repository\org\springframework\spring-aop\7.0.6\spring-aop-7.0.6.jar;D:\develop-tools\Environment\Maven\maven-repository\org\springframework\spring-beans\7.0.6\spring-beans-7.0.6.jar;D:\develop-tools\Environment\Maven\maven-repository\org\springframework\spring-context\7.0.6\spring-context-7.0.6.jar;D:\develop-tools\Environment\Maven\maven-repository\io\micrometer\micrometer-observation\1.16.4\micrometer-observation-1.16.4.jar;D:\develop-tools\Environment\Maven\maven-repository\io\micrometer\micrometer-commons\1.16.4\micrometer-commons-1.16.4.jar;D:\develop-tools\Environment\Maven\maven-repository\org\springframework\spring-core\7.0.6\spring-core-7.0.6.jar;D:\develop-tools\Environment\Maven\maven-repository\commons-logging\commons-logging\1.3.5\commons-logging-1.3.5.jar;D:\develop-tools\Environment\Maven\maven-repository\org\jspecify\jspecify\1.0.0\jspecify-1.0.0.jar;D:\develop-tools\Environment\Maven\maven-repository\org\springframework\spring-expression\7.0.6\spring-expression-7.0.6.jar;D:\develop-tools\Environment\Maven\maven-repository\org\springframework\spring-web\7.0.6\spring-web-7.0.6.jar;D:\develop-tools\Environment\Maven\maven-repository\org\springframework\spring-jdbc\7.0.6\spring-jdbc-7.0.6.jar;D:\develop-tools\Environment\Maven\maven-repository\org\springframework\spring-tx\7.0.6\spring-tx-7.0.6.jar MyTest
People{name='张磊', dog=com.zhang.pojo.Dog@22635ba0, cat=com.zhang.pojo.Cat@13c10b87}
miao
wang

Process finished with exit code 0

7.2、ByName自动装配

Spring 直接拿你类里的 属性名,去 Spring 容器里找 id/name 一模一样 的 Bean,找到就自动注入,找不到就为 null。

<?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="people" class="com.zhang.pojo.People" 
      autowire="byName">
    <property name="name" value="张磊"/>
</bean>
    <bean id="cat" class="com.zhang.pojo.Cat"/>
    <bean id="dog" class="com.zhang.pojo.Dog"/>
</bea

可以看到上面我们没有为people中的bean属性配置ref

image.png byName 匹配规则 → 忽略大小写,只看字母内容是否一致

7.3、ByTyple自动装配

Spring 按属性的类型去容器里找同类型 Bean,找到一个就自动注入,找不到或找到多个就报错。

<bean id="people" class="com.zhang.pojo.People"
      autowire="byType">
    <property name="name" value="张磊"/>
</bean>
    <bean id="cat" class="com.zhang.pojo.Cat"/>
    <bean id="dog" class="com.zhang.pojo.Dog"/>

由于是依据bean类型来自动装配,所以bean可以没有name

<?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="people" class="com.zhang.pojo.People"
      autowire="byType">
    <property name="name" value="张磊"/>
</bean>
    <bean  class="com.zhang.pojo.Cat"/>
    <bean  class="com.zhang.pojo.Dog"/>
</beans>

image.png

如果同一类型有多个实例。就会报错

image.png

7.4、使用注释实现自动装配

在基于XML的Spring设置中,你可以包含以下配置标签以启用 与基于注释的配置混合搭配:

<?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>

开启自动装配后的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: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="people" class="com.zhang.pojo.People"
    >
        <property name="name" value="张磊"/>
    </bean>
    <bean  class="com.zhang.pojo.Cat"/>
    <bean  class="com.zhang.pojo.Dog"/>
</beans>

在实体类中的bean字段添加 @Autowired 注解

image.png 实现自动装配

image.png @Autowired

直接在属性上使用即可!也可以在set方式上使用!

使用Autowired我们可以不用编写Set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在

科普:

@Nullable 字段标记了这个注解,说明这个字段可以为null;

public @interface Autowired {

boolean required() default true;

}
  • 如果@Autowired自动装配的环境比较复杂,一个类型的bean字段有多个不同name的实例时,
  • 自动装配无法通过一个注解【@Autowired】完成的时候、我们可以使用@Qualifier(value="xxx")去配置@Autowired的使用,指定一个唯一的bean对象注入!
public class People {

    @Autowired
    @Qualifier(value="cat111")
    private Cat cat;

    @Autowired
    @Qualifier(value="dog222")
    private Dog dog;
    private String name;

8、使用注解进行开发

1. bean @Component

  • @Component注解相当于 bean id="people" class="com.zhang.pojo.People">
  • 在拿出这个Bean时用首字母小写的类名user
package com.zhang.pojo;

import org.springframework.stereotype.Component;

@Component
public class User {
    private String name="zhang";
    private int age=17;
<?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/>-->
    <context:component-scan base-package="com.zhang.pojo"/>

</beans>
  • <context:annotation-config />只激活注解功能(@Autowired、@Resource 等能生效),不扫描、不注册 Bean

  • <context:component-scan base-package="..." />)扫描包下的 @Component、@Service、@Repository 并注册成 Bean同时自带 annotation-config 的全部功能

image.png

2. 属性如何注入 @Value

image.png

真正常用、核心的用法:从配置文件读

@Value("${user.name}")
private String name;

在 XML 里加载配置文件

<!-- 加载 properties 配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>

<!-- 包扫描(让@Value生效) -->
<context:component-scan base-package="com.zhang"/>

它会去读 .properties.yml 里的配置:

3. 衍生的注解

@Component 有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!

  • dao 【@Repository】

  • service 【@Service】

  • controller 【@Controller】

    这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean

4. 自动装配置

参见7.4

5. 作用域 @Scope

  • 改变bean的作用域为单例或原型
@Component
@Scope("singleton")
public class User {
    @Value("zhanglei")
    private String name;
    private int age=17;

参见6.4

6. 小结

xml与注解:

  • xml更加万能,适用于任何场合!维护简单方便

  • 注解不是自己类使用不了,维护相对复杂!

xml与注解最佳实践:

  • xml用来管理bean;

  • 注解只负责完成属性的注入; 也即:用@Value代替Set注入

9、完全用java文件配置Spring

@Configuration 作用:标记一个类为 Spring 配置类,替代原来的 XML 配置文件。

  • @Configuration 是 Spring 顶级注解

它一出现,Spring 就会自动开启注解支持包括:

  • @Value
  • @Autowired
  • @Resource

只要你用 @Configuration 或 @Bean 注册 Bean,Spring 就自动开启注解支持,@Value 直接能用!不需要包扫描,不需要 XML,不需要任何其他配置!

package com.zhang.config;

import com.zhang.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
// Configuration表示这个也会Spring容器托管,注册到容器中,因为他本来就是一个@Component
//代替xml配置文件
@Configuration
//`@ComponentScan` = 自动批量注册带有@Conponent的类注册为 Bean
//如果你写了包扫描,就不要写@Bean,不然会注册两个实例,除非扫描的类没有@Conponent
//包扫描和 @Bean 不会冲突;@Component 和 @Bean 同时存在同一个类上,才会重复注册 Bean。
@ComponentScan("com.zhang")
public class MyConfig {

//注册一个bean , 就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean标签中的id属性
//这个方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User user() {
        return new User();
    }
}
package com.zhang.pojo;

import org.springframework.beans.factory.annotation.Value;

public class User {
    private int id;
    @Value("zhanglei")
    private String name;


  • 如果完全使用了配置类方式去做,我们就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的class对象加载!
import com.zhang.config.MyConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context =
                new AnnotationConfigApplicationContext(MyConfig.class);
        Object user = context.getBean("user");
        System.out.println(user);
    }
}

image.png

10、代理模式

为什么要学习代理模式?因为这就是SpringAOP的底层!【SpringAOP 和 SpringMVC】

代理模式的分类:

  • 静态代理
  • 动态代理

image.png

10.1、静态代理

角色分析:

  • 抽象角色:一般会使用接口或者抽象类来解决
  • 真实角色:被代理的角色
  • 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
  • 客户:访问代理对象的人!

代码步骤:

  1. 接口

image.png 3. 真实角色

image.png 5. 代理角色

image.png 7. 客户端访问代理角色

image.png 代理模式的好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务

  • 公共也就就交给代理角色!实现了业务的分工!

  • 公共业务发生扩展的时候,方便集中管理!

缺点:

  • 一个真实角色就会产生一个代理角色;代码量会翻倍开发效率会变低~

10.2、更深层的静态代理理解

  • 在我们面向接口编程时,为了好维护、好替换、好测试,我们会把要的业务写在接口,具体的实现放在实现类,就像菜单和厨师的关系
package com.zhang.demo01;

public interface UserService {
    void add();
    void delete();
    void update();
    void find();
}
package com.zhang.demo01;

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 find() {
        System.out.println("查找了一个用户");
    }
}
package com.zhang.demo01;

public class Client {
    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();
        userService.add();
    }
}
  • 这时我们增添了一个需求,为每个功能实现添加日志
  • 如果在实现类里加日志,会违反「开闭原则」,破坏业务代码的纯粹性,代码会越来越乱
  • 实现类就应该只实现接口代码,不应该去修改老旧代码
  • 不会拆墙改结构来装修,而是在外面加装饰(代理)
package com.zhang.demo01;

public class UserServiceImplProxy implements UserService {
    private UserServiceImpl userServiceImpl;
    public void setUserServiceImpl(UserServiceImpl userServiceImpl) {
        this.userServiceImpl = userServiceImpl;
    }

    @Override
    public void add() {
        log("add");
        userServiceImpl.add();
    }

    @Override
    public void delete() {
        log("delete");
        userServiceImpl.delete();
    }

    @Override
    public void update() {
        log("update");
        userServiceImpl.update();
    }

    @Override
    public void find() {
        log("find");
        userServiceImpl.find();
    }
    private void log(String msg) {
        System.out.println("调用了" + msg + "方法");
    }
}
  • 直接改实现类:侵入代码、冗余、违反设计原则。

  • 用代理:不侵入、不修改、统一管理、功能分离。

image.png

image.png

10.3、动态代理

  • 动态代理和静态代理角色一样

  • 动态代理的代理类是动态生成的,不是我们直接写好的!

  • 动态代理分为两大类:基于接口的动态代理,基于类的动态代理

    • 基于接口 --- JDK 动态代理 【我们在这里使用】
    • 基于类:cglib
    • java字节码实现 : javasist

需要了解两个类:Proxy:代理,InvocationHandler:调用处理程序

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//implements InvocationHandler:表示这个类是代理的 处理器 ,专门处理代理方法的调用
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object target;
//给真实对象赋值你要代理谁,就把谁传进来。
public void setTarget(Object target) {
    this.target = target;
}

//生成得到代理类
//类加载器,getClassLoader:给 JDK 用来加载自动生成的代理类,因为 JDK 不能自己 new 类加载器
//target.getClass().getInterfaces():你生成的代理类,要实现哪些接口?
//this:绑定到当前这个 InvocationHandler,也就是说:
//以后别人调用代理的任何方法,都必须跑到当前这个类的 invoke () 方法里执行
public Object getProxy(){
    return Proxy.newProxyInstance(this.getClass().getClassLoader(),
            target.getClass().getInterfaces(), this);
}

//处理代理实例,并返回结果:
//使用proxy.add () 时,表面没调用 invoke,但 JDK 自动生成的代理类 $Proxy0 内部,
//已经帮你偷偷调用了 invoke,并且把方法、参数通过反射全都传进去
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    log(method.getName());
    Object result = method.invoke(target, args);
    return result;
}

public void log(String msg){
    System.out.println("执行了"+msg+"方法");
}
}
public class Client {
    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();
        ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
        proxyInvocationHandler.setTarget(userService);//设置需要代理的对象
//        动态生成代理类
        UserService proxy = (UserService) proxyInvocationHandler.getProxy();
        proxy.add();
    }
}

image.png

动态代理的好处:

  • 可以使真实角色的操作更加纯粹!不用去关注一些公共的业务
  • 公共也就就交给代理角色!实现了业务的分工!
  • 公共业务发生扩展的时候,方便集中管理!
  • 一个动态代理类代理的是一个接口,一般就是对应的一类业务
  • 一个动态代理类可以代理多个类,只要是实现了同一个接口即可

11、AOP

AOP(Aspect-Oriented Programming)  即面向切面编程,是一种编程范式,它允许开发者将横切关注点(如日志、事务、安全等)从业务逻辑中分离出来,实现模块化。

简单理解:AOP 就像给现有代码“增强功能”,而不用修改原有代码。代理模式是AOP编程思想的一种体现

AOP的核心概念

要想使用Aop配置标签除了基本的springwebmvc依赖,还需要j方面依赖aspectj

<!-- Source: https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>7.0.6</version>
    <scope>compile</scope>
</dependency>
<!-- Source: https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>7.0.6</version>
    <scope>compile</scope>
</dependency>
<!-- Source: https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.25.1</version>
    <scope>runtime</scope>
</dependency>
   <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.9.6</version>
    </dependency>

1. 切面(Aspect)

横切关注点的模块化,比如日志切面、事务切面

切面 = 你要添加的功能 + 定义这个功能在哪里执行

  • advice-ref 指向的就是您要添加的具体功能代码,就是通知。
  • pointcut-ref → aop:pointcut → expression表达式 → 匹配业务类的方法
方式一:使用Spring自带APi实现

image.png

<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.zhang.demo02.UserService.*(..))"/>
<!--          advice-ref: 通知   pointcut-ref:切入点-->
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="brforeLog" pointcut-ref="pointcut"/>
</aop:config>

image.png

方式二:自定义类
public class DiyPointCut {
    public void before() {
        System.out.println("before执行了");
    }
    public void after() {
        System.out.println("after执行了");
    }
}
    <bean id="diy" class="com.zhang.demo02.diy.DiyPointCut"/>
    <aop:config>
<!--        声明一个切面,并引用一个已经定义好的Bean,这个是自定义的-->
        <aop:aspect ref="diy">
<!--            定义切入点,指定哪些方法需要被增强-->
<!--            - execution() - 切入点表达式的固定格式
                - * >>> 任意返回值类型
                - com.zhang.demo02.UserServiceImpl >>> 要增强的目标类
                - .* >>> 该类的所有方法
                - (..) >>> 任意参数类型和个数      -->
            <aop:pointcut id="point"
                          expression="execution(* com.zhang.demo02.UserServiceImpl.*(..))"/>
<!--             配置前置通知,在目标方法执行之前执行-->
            <aop:before method="before" pointcut-ref="point"/>
<!--             配置后置通知,在目标方法执行之后执行(无论是否异常)-->
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>

    </aop:config>

image.png

方式三:通过注解
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class AnnotationPointcut {
    @Before("execution(* com.zhang.demo02.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("before执行了 AnnotationPointcut");
    }
    @After("execution(* com.zhang.demo02.UserServiceImpl.*(..))")
    public void after() {
        System.out.println("after执行了 AnnotationPointcut");
    }
}
<bean id="AnnotationPointcut" class="com.zhang.demo02.AnnotationPointcut"/>
<!--    开启aop注解-->
<aop:aspectj-autoproxy/>

image.png

2. 连接点(JoinPoint)

程序执行中可以插入切面的点,如方法调用、异常抛出等

3. 通知(Advice)

切面在特定连接点执行的动作,有5种类型:

  • @Before:方法执行前
  • @After:方法执行后
  • @AfterReturning:方法正常返回后
  • @AfterThrowing:方法抛出异常后
  • @Around:环绕通知(最强大)

4. 切入点(Pointcut)

匹配连接点的表达式,定义通知在哪些方法上执行

5. 目标对象(Target Object)

被通知增强的对象

6. 织入(Weaving)

将切面应用到目标对象创建代理对象的过程

12、整合Mybatis

步骤:

  1. 导入相关jar包

    • junit
    • mybatis
    • mysql数据库
    • spring相关的
    • aop织入
    • mybatis-spring【new】
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>7.0.6</version>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>9.6.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.19</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.25.1</version>
        </dependency>
        <!-- Source: https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<!--        spring操作数据库的依赖包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>7.0.6</version>
            <scope>compile</scope>
        </dependency>

        <!-- Source: https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<!--        mybatis-spring的整合包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>4.0.0</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
  1. 编写配置文件

  2. 测试

12.1、回忆mybatis

  1. 编写实体类
public class User {
    private int id;
    private String name;
    private String pwd;
  1. 编写核心配置文件
<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTime=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper class="com.zhang.mapper.UserMapper"/>
    </mappers>
</configuration>
  1. 编写接口
import com.zhang.pojo.User;

import java.util.List;

public interface UserMapper {
    List<User> getUserList();
}
  1. 编写Mapper.xml
<?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.zhang.mapper.UserMapper">
    <select id="getUserList" resultType="com.zhang.pojo.User">
        select * from mybatis.user;
    </select>
</mapper>
  1. 测试
import com.zhang.mapper.UserMapper;
import com.zhang.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyTest {
    @Test
    public void test() {
        String resource = "mybatis-config.xml";
        try {
            InputStream in = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = mapper.getUserList();
            for (User user : userList) {
                System.out.println(user);
            }
            sqlSession.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

12.2、Mybatis-spring

1. 编写数据源配置

<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
   <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
   <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTime=GMT"/>
   <property name="username" value="root"/>
   <property name="password" value="123456"/>
</bean>

2. sqlSessionFactory

  • sqlSessionFactoryBean 是为了创建 SqlSessionFactory,而 SqlSessionFactory 用于创建 SqlSession在创建工厂时就需要配置好MyBatis的核心信息,因为工厂一旦创建就不可变。
  • mapperLocations 告诉 SqlSessionFactory:"在创建你的时候,去这些位置加载SQL文件"。所以 SqlSessionFactory 内部有一个 Configuration 对象,里面存储了所有解析好的SQL。
  • sqlSession.getMapper()  只是从 Configuration 中查找对应接口的SQL信息
  • MyBatis的所有配置(无论是全局配置文件还是Mapper映射文件)都是为 SqlSessionFactory 服务的!SqlSessionFactory 就像一个工厂的设计图纸和生产规范,一旦建成就不能改变。而 SqlSession 只是这个工厂生产出来的具体工人,工人只能按照工厂的规范去工作。
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource"/>
<!--        绑定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/zhang/mapper/*.xml"/>
    </bean>

3. sqlSessionTemplate

SqlSessionTemplate,它是线程安全的,可以在多个线程中共享使用。相比直接使用原生SqlSession,这个设计:

  1. 避免了线程安全问题
  2. 自动管理数据库连接的生命周期SqlSessionTemplate 会自动管理 SqlSession 的生命周期,你完全不需要(也不应该)手动关闭。
  3. 与Spring的事务管理无缝集成
  4. 简化了代码,不需要手动提交/回滚/关闭
<!--    SqlSessionTemplate就相当于sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--        因为这个类没有set方法,所以只能构造器注入-->
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

4. 需要给接口加实现类 【非最佳实践】

package com.zhang.mapper;

import com.zhang.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements UserMapper {
    private SqlSessionTemplate sqlSession;
    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }
    @Override
    public List<User> getUserList() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.getUserList();
    }
}
- 最佳实践是下面的      
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;  // 直接注入,无需getMapper
    
    public List<User> getUsers() {
        return userMapper.getUserList();  // 最简洁
    }
}        

5. 将自己写的实现类,注入到Spring中

<bean id="userMapper" class="com.zhang.mapper.UserMapperImpl">
    <property name="sqlSession" ref="sqlSession"/>
</bean>

6. 测试使用即可!

image.png

13、声明式事务

1、回顾事务

  • 把一组业务当成一个业务来做;要么都成功,要么都失败!
  • 事务在项目开发中,十分的重要,涉及到数据的一致性问题,不能马虎!
  • 确保完整性和一致性;

事务ACID原则:

原子性 (Atomicity)

事务中的所有操作要么全部成功,要么全部失败,不存在部分成功的情况。

一致性 (Consistency)

事务执行前后,数据必须从一个正确的状态变为另一个正确的状态,不破坏任何业务规则(如:转账前后总金额不变)。

隔离性 (Isolation)

多个事务同时执行时,彼此之间互不干扰,就像在排队执行一样。

持久性 (Durability)

事务一旦提交,对数据的修改就是永久的,即使系统崩溃也不会丢失。

2、声明式事物

在如下实现类代码中,同时调用了查,增,删;看作一个事务

@Override
public int addUser(User user) {
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    int i = mapper.addUser(user);
    getUserList();
    deleteUser(i);
    return i;
}

但是如下图,删除语法出现了错误

image.png 造成了下面的结果,依据事务的隔离性应当成功的add,也应该回滚,没有事物管理导致结果增加成功而删除未成功,理应全部失败才对

image.png

image.png

  1. 配数据源(连上数据库)
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTime=GMT"/>
    <property name="username" value="root"/>
    <property name="password" value="123456"/>
</bean>
  1. 配工厂(MyBatis工作)
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource"/>
<!--        绑定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/zhang/mapper/*.xml"/>
    </bean>
  1. 配事务管理器(谁来管事务)
<bean id="transactionManger"
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="datasource"/>
</bean>
  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"
       xmlns:tx="http://www.springframework.org/schema/tx"      <!-- 添加这一行 -->
       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/tx               <!-- 添加这一行 -->
           http://www.springframework.org/schema/tx/spring-tx.xsd <!-- 添加这一行 -->
           http://www.springframework.org/schema/aop              <!-- 添加这一行 -->
           http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 添加这一行 -->
<tx:advice id="txAdvice" transaction-manager="transactionManger">
    <tx:attributes>
        <!-- 匹配所有以add、get、delete开头的方法 -->
        <tx:method name="get" propagation="REQUIRED"/>
        <tx:method name="add"/>
        <tx:method name="delete"/>
    </tx:attributes>
</tx:advice>
  1. 配AOP切面(应用到哪层代码)
<aop:config>
    <aop:pointcut id="service" expression="execution(* com.zhang.mapper.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="service"/>
</aop:config>

现在的效果

image.png

image.png

注解方式实现声明式事务

<!-- 事务管理器 -->
    <bean id="transactionManager" 
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- 关键:开启注解事务支持 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
   // 方法级别:只有这个方法有事务
    @Transactional
    public void addUser(User user) {
        userMapper.insertUser(user);
    }
    
    // 也可以加在类上:类中所有方法都有事务
 // 完整配置示例
    @Transactional(
        propagation = Propagation.REQUIRED,      // 传播行为
        isolation = Isolation.DEFAULT,           // 隔离级别
        timeout = 30,                            // 超时时间(秒)
        readOnly = false,                        // 是否只读
        rollbackFor = Exception.class,           // 哪些异常回滚
        noRollbackFor = BusinessException.class  // 哪些异常不回滚
    )

image.png