Maxon's Blog

Spring 笔记

3

Spring 学习笔记

一. 简介

  • Spring : 春天---> 给软件行业带来了春天!
  • 2002年,首次推出了Spring框架的雏形---Interface21框架!
  • 2004年3月24日,Spring Framework 1.0 final正式出现在我们的视野中!
  • Rod Johnson :Spring框架的创始人,同时也是SpringSource的联合创始人。Spring是面向切面编程(AOP)和控制反转(IoC)的容器框架。
  • Spring理念:使现有的技术更加容易使用,本身是一个大杂烩.整合了现有的技术框架!
  • SSH:Struts2 + Spring + Hibernate
  • SSM:SpringMVC + Spring + Mybatis

官网: https://spring.io/projects/spring-framework#overview

官方下载地址: repo.spring.io

Github地址 : Spring (github.com)

导包:

Xml
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.11</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.11</version>
</dependency>

1.优点

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

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

2.Spring的组成

image-20220830114004085

3.拓展

现代化的Java开发,说白了就是基于Spring的开发!

  • Spring Boot
    • 一个快速开发的脚手架
    • 基于Spring Boot 可以快速开发单个微服务.
    • 约定大于配置
  • Spring Cloud
    • 基于Spring Boot实现

因为现在大多数公司都在使用SpringBoot 进行快速开发**,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC!!

4.弊端:

发展了太久之后,违背了原来的理念! 配置十分繁琐! 人称 配置地狱 !!!

二. IOC 理论推导

原先的设计模式:

  1. UserDao接口

    Java
    package org.mecca.dao;
    
    public interface UserDao {
        void getUser();
    }
    
  2. UserDaoImpl实现类

    Java
    package org.mecca.dao;
    public class UserDaoImpl implements UserDao{
        @Override
        public void getUser() {System.out.println("默认获取用户数据!!");}
    }
    
    
    Java
    package org.mecca.dao;
    public class UserDaoMysqlImpl implements UserDao{
        @Override
        public void getUser() {System.out.println("Mysql 获取 用户数据!!");}
    }
    
  3. UserService 业务接口

    Java
    package org.mecca.service;
    import org.mecca.dao.UserDao;
    public interface UserService {
        void getUser();
        void setUserDao(UserDao userDao);
    }
    
  4. UserServiceImpl 业务实现类

    Java
    package org.mecca.service;
    import org.mecca.dao.UserDao;
    import org.mecca.dao.UserDaoImpl;
    import org.mecca.dao.UserDaoMysqlImpl;
    
    public class UserServiceImpl implements UserService{
        private UserDao userDao;
        //利用set进行动态实现值的注入!!
        public void setUserDao(UserDao userDao) {this.userDao = userDao;}
        @Override
        public void getUser() {userDao.getUser();}
    }
    
    
  5. Test

    Java
    import org.mecca.dao.UserDaoImpl;
    import org.mecca.dao.UserDaoMysqlImpl;
    import org.mecca.service.UserService;
    import org.mecca.service.UserServiceImpl;
    
    public class MyTest {
        public static void main(String[] args) {
            //用户实际调用的是业务层 dao 他们不需要接触
            UserService userService = new UserServiceImpl();
            userService.setUserDao(new UserDaoImpl());
            userService.getUser();
        }
    }
    

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

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

Java
 private UserDao userDao;

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

IOC原型:

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

IOC本质:

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

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

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

三. HelloSpring

beans.xml

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="hello" class="org.mecca.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>
</beans>

Hello.java

Java
package org.mecca.pojo;
public class Hello {
    private String str;
    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }

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

Mytest.java

Java
import org.mecca.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
    public static void main(String[] args) {
        // create and configure beans
        //获取Spring上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

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

image-20211024175737675

这个过程就叫控制反转:

  • 控制: 谁来控制对象的创建,传统的应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的.
  • 反转: 程序本身不创建对象,而变成被动的接收对象
  • 依赖注入: 就是利用set方法来进行注入
  • IOC 是一种编程思想,由主动的编程变成被动的接收

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

四. IOC创建对象的方式

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

  2. 假设我们要使用有参构造

    1. Xml
      <constructor-arg index="0" value="Sping"/>
      
    2. Xml
      <constructor-arg type="java.lang.String" value="Spring"/>     不建议使用
      
    3. Xml
      <constructor-arg name="name" value="Spring"/>          最简单
      

总结:在配置文件加载的时候 容器中管理的对象就已经被初始化了!!

五. Spring配置

1.别名

Xml
<alias name="user" alias="userNew"/>

如果使用了别名,我们也可以通过别名获取bean

2.Bean的配置

Xml
<!--
id: bean的唯一标识符,也相当于对象名
class: bean对象所对应的全限定名: 包名+类型
name:也是别名  name可以取多个别名
-->
<bean id="userT" class="org.mecca.pojo.UserT" name="userT2,U2" >
    <property name="name" value="Spring"/>
</bean>

3.import

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

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

使用的时候直接使用总的xml就可以了!!

Xml
<import resource="beans.xml"/>
<import resource="bean2.xml"/>
<import resource="bean3.xml"/>

六. DI依赖注入

1.构造器注入

前面已经说明

2. set方式注入

  • 依赖注入: Set注入!
    • 依赖: bean对象的创建依赖于容器 !
    • 注入: bean对象中的所有属性,由容器来注入!

环境搭建

1.复杂类型

2.真实测试对象

Java
import org.mecca.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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());
//      Student{name='Aealen',
//      address=Address{address='芜湖'},
//      books=[红楼梦, 西游记, 三国演义, 水浒传],
//      hobbies=[听歌, 看电影, 敲代码],
//      card={身份证=1111111111111111111, 银行卡=123123342342341},
//      games=[LOL, CS, OW, BOB, COC],
//      wife='null',
//      info={学号=19101912, 性别=男, 年级=五年级, 年龄=90}}
    }
}
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="org.mecca.pojo.Address">
        <property name="address" value="芜湖"/>
    </bean>

    <bean id="student" class="org.mecca.pojo.Student">
        <!--    普通注入  value`-->
        <property name="name" value="Aealen"/>
        <!--    bean注入 ref-->
        <property name="address" ref="address"/>
        <!--    数组注入  value`-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>三国演义</value>
                <value>水浒传</value>
            </array>
        </property>
        <!--    List注入  value`-->
        <property name="hobbies">
            <list>
                <value>听歌</value>
                <value>看电影</value>
                <value>敲代码</value>
            </list>
        </property>
        <!--    Map注入  value`-->
        <property name="card">
            <map>
                <entry key="身份证" value="1111111111111111111"/>
                <entry key="银行卡" value="123123342342341"/>
            </map>
        </property>

        <!--    Set注入  value`-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>CS</value>
                <value>OW</value>
                <value>BOB</value>
                <value>COC</value>
            </set>
        </property>
        <!--    null -->
        <property name="wife">
            <null/>
        </property>
        <!--    Properties-->
        <property name="info">
            <props>
                <prop key="学号">19101912</prop>
                <prop key="性别"></prop>
                <prop key="年级">五年级</prop>
                <prop key="年龄">90</prop>
            </props>
        </property>
    </bean>
</beans>

3.拓展方式注入

我们可以使用p命名空间和c命名空间进行注入!!

p:namespace

Xml
xmlns:p="http://www.springframework.org/schema/p"


<!--p 命名空间注入 可以直接注入属性的值-->
<bean id="user" class="org.mecca.pojo.User" p:name="Aealen" p:age="18"/>

c:namespace

Xml
xmlns:c="http://www.springframework.org/schema/c"

<!--c 命名空间注入 可使用构造器注入-->
<bean id="user2" class="org.mecca.pojo.User" c:age="18" c:name="Aealen"/>

注意点: p命名和c命名空间不能直接使用,要导入xml约束

4. Bean作用域

ScopeDescription
singleton(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.(默认)将单个 bean 定义范围限定为每个 Spring IoC 容器的单个对象实例。
prototypeScopes a single bean definition to any number of object instances.将单个 bean 定义范围限定为任意数量的对象实例。
requestScopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.将单个 bean 定义范围限定为单个 HTTP 请求的生命周期。也就是说,每个 HTTP 请求都有自己的 bean 实例,该 bean 实例是在单个 bean 定义的后面创建的。仅在 web-aware Spring ApplicationContext 的上下文中有效。
sessionScopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.将单个 bean 定义范围限定为 HTTP 会话的生命周期。仅在 web-aware Spring ApplicationContext 的上下文中有效。
applicationScopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.将单个 bean 定义范围限定为 ServletContext 的生命周期。仅在 web-aware Spring ApplicationContext 的上下文中有效。
websocketScopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.将单个 bean 定义范围限定为 WebSocket 的生命周期。仅在 web-aware Spring ApplicationContext 的上下文中有效。

4.1单例模式(Spring 默认机制)

Xml
<bean id="user2" class="org.mecca.pojo.User" c:age="18" c:name="Aealen" scope="singleton"/>

4,2原型模式:每次从容器中get的时候都会产生一个新的对象

Xml
<bean id="user2" class="org.mecca.pojo.User" c:age="18" c:name="Aealen" scope="prototype"/>

4.3其余的 request session application这些个只能在web开发中使用到!

七. Bean的自动装配

  • 自动装配是Spring慢速Bean依赖的一种方式!
  • Spring会在上下文中自动寻找并自动给Bean装配属性!

在Spring中有三种自动装配的方式:

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

1. 测试

  • 环境: 一个人有两个宠物

2. byName 自动装配

Xml
<bean id="cat" class="org.mecca.pojo.Cat"/>
<bean id="dog" class="org.mecca.pojo.Dog"/>
<bean id="human" class="org.mecca.pojo.Human" autowire="byName">
    <property name="name" value="Aealen"/>
</bean>
  • 会自动在容器上下文中查找和自己对象set方法后面的值对应的bean的id

3. byType 自动装配

Xml
<bean id="cat22" class="org.mecca.pojo.Cat"/>
<bean id="dog11" class="org.mecca.pojo.Dog"/>
<bean id="human" class="org.mecca.pojo.Human" autowire="byType">
    <property name="name" value="Aealen"/>
</bean>
  • 会自动在容器上下文中查找和自己对象属性类型相同的bean

小结:

  • byName方法自动装配只看名字,若是id不一样则无法装配
  • byName 的时候需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
  • byType 的时候需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!
  • byType方法自动装配只看类型,若是类型不一样则无法装配

4. 使用注解实现自动装配

JDK1.5 支持的注解,Spring2.5就支持注解了!

Xml
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML. The short answer is “it depends.”

要使用注解须知:

  • 导入约束

  • 配置注解的支持

    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/>
    
    </beans>
    

    @Autowired

  • 直接在属性上使用即可,也可以在set方法上使用.

  • 使用Autowired,我们可以不用再编写set方法了,前提是你这个自动装配的属性再IOC(Spring)容器中存在,且符合名字byName

    Xml-dtd
    @Nullable  字段标记了这个注解,说明这个字段可以为 NULL
    
    Java
    public @interface Autowired {
        boolean required() default true;
    }
    如果显式地定义了 @Autowired(required=false) 那么这个对象就可以为空,否则不能为空
    

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

@Resource

Java自带的注解, JDK8之后取消!!

@Autowired和@Resource的区别:

  • 都是用来自动装配的,都可以放在属性字段上
  • @Autwired 默认通过byType的方式实现,而且必须要求这个对象存在! 否则 空指针
  • @Resource 默认通过byName的方式实现,如果找不到名字,则通过byType,如果两个都找不到的情况就报错!
  • 执行顺序不同:@Autwired 默认通过byType的方式实现,@Resource 默认通过byName的方式实现

八. Spring使用注解开发

在Spring4之后要使用注解开发必须要保证AOP的包导入了!

使用注解需要导入context约束,增加注解的支持!

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:component-scan base-package="org.mecca.pojo"/>
    <context:annotation-config/>

</beans>

1.bean

Java
 @Component 组件,放在类上,说明这个类被Spring管理了!就是所谓的bean

2.属性如何注入

Java
package org.mecca.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//等价于在bean注册了bean
@Component
public class User {
    public String name;
    //相当于<property name="name value="Aealen"/>
    @Value("Aealen")
    public void setName(String name) {
        this.name = name;
    }
}

3.衍生的注解

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

  • dao @Repository
  • service @Service
  • controller @Controller
  • 这四个注解功能都是一样的,都是代表将某个类注册到Spring容器中, 装配!!

4.自动装配

5.作用域

Java
@Scope("prototype") 

6.小结

xml与注解:

  • xml 更加万能,适用于任何场合,维护简单方便!
  • 注解 不是自己的类是用不了,维护相对复杂!

最佳实践:

  • xml用来管理bean
  • 注解只用来完成属性的注入!
  • 我们在使用的过程中只需要注意一个问题:必须让注解生效,必须要开启支持

九.基于Java方式配置Spring

我们现在要完全不使用Spring的xml配置了,全权交给Java来做!

JavaConfig是Spring的一个子项目,再Spring4之后,他成为了核心功能!

Java
@Configuration  //代表这是个配置类 , 就和之前的beans.xml是一样的
@Import(NewConfig.class) //可以导入配置类

//注册一个bean就相当于我们之前写的一个bean 标签
//这个方法的名字就相当于 bean 标签中的id 属性
//这个方法的返回值就相当于Bean标签中的class属性
@Bean
public User getUser(){
    return new User();//返回要注入bean的对象
}

//如果完全使用了配置类方式去实现,我们只能通过AnnotationConfig 上下文来获取容器,通过配置类的class对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);


这种纯Java的配置方式,在SpringBoot中随处可见! SSM!!

十. 代理模式

为什么要学习代理模式?

因为这就是SpringAOP的底层! [SpringAOP 和 SpringMVC]

代理模式的分类:

  • 静态代理:
  • 动态代理:

image-20211111103343634

1. 静态代理

角色分析:

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

代理模式的好处:

  • 可以使真实角色的操作更加纯粹,不用去关系一些公共的业务!
  • 公共业务就交给了代理角色!实现了业务的分工
  • 公共业务发生扩展的时候,方便集中管理!

缺点:

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

2.动态代理

  • 动态代理和静态代理的角色一样
  • 动态代理的类是动态生成的,不是我们直接写好的!
  • 动态代理分为两大类: 基于接口的动态代理,基于类的动态代理
    • 基于接口: JDK动态代理
    • 基于类 : cglib
    • java字节码实现: javasist

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

InvocationHandler

InvocationHandler is the interface implemented by the invocation handler of a proxy instance.

Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke method of its invocation handler.

Proxy动态代理工具类

Java
package org.mecca.client.demo04;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//我们会用这个类自动生成代理
public class ProxyInvocationHandle implements InvocationHandler {
    //被代理的接口
    private Object target;
    public void  setTarget(Object target){
        this.target=target;
    }
    //生成得到代理类
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }
    //处理代理实例并返回结果
    @Override
    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+"方法");
    }
}

十一. AOP

1. 什么是AOP

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

img

2. AOP在Spring中的作用

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

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

3. 使用Spring实现Aop

导包

Xml
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.8.RC1</version>
</dependency>
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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">



<!--    注册Bean-->
    <bean id="userService" class="org.mecca.service.UserServiceImpl"/>
    <bean id="log" class="org.mecca.log.Log"/>
    <bean id="afterLog" class="org.mecca.log.AfterLog"/>

<!--    方式一: 使用原生的Spring API接口-->
<!--    配置Aop  导入aop的约束-->
    <aop:config>
<!--    切入点:expression表达式   execution(要执行的位置!)-->
        <aop:pointcut id="pointcut" expression="execution(* org.mecca.service.UserServiceImpl.*(..))"/>

<!--    执行环绕增加!-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>

    </aop:config>

<!--    方式二: 自定义类-->
    <bean id="diy" class="org.mecca.diy.DiyPointCut"/>
    <aop:config>
<!--        自定义切面 ref引用-->
        <aop:aspect ref="diy">
<!--            切入点-->
            <aop:pointcut id="point" expression="execution(* org.mecca.service.UserServiceImpl.*(..))"/>
<!--            通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

</beans>

方式三: 注解实现AOP

Java
package org.mecca.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;
//使用注解方式实现AOP
@Aspect//标注这个类是一个切面
public class AnnotationPointCut {
    @Before("execution(* org.mecca.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("===方法执行前===");
    }

    @After("execution(* org.mecca.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("===方法执行后===");
    }
    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
    @Around("execution(* org.mecca.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕前");

        //执行方法
        Object proceed = joinPoint.proceed();

        System.out.println("环绕后");
    }
}
Xml
<!--    方式三:-->
    <bean id="annotationPointCut" class="org.mecca.diy.AnnotationPointCut"/>
<!--    开启注解支持-->
    <aop:aspectj-autoproxy/>

image-20211114202909785