学习笔记_Spring_day03

AOP相关概念

AOP相关术语

Joinpoint(连接点): 被拦截到的方法.
Pointcut(切入点): 我们对其进行增强的方法.
Advice(通知/增强): 对切入点进行的增强操作
包括前置通知,后置通知,异常通知,最终通知,环绕通知
Weaving(织入): 是指把增强应用到目标对象来创建新的代理对象的过程。
Aspect(切面): 是切入点和通知的结合

AOP思想的实现一般都是基于代理模式 ,在JAVA中一般采用JDK动态代理模式,但是我们都知道,JDK动态代理模式只能代理接口而不能代理类。因为Spring AOP 同时支持 CGLIB、ASPECTJ、JDK动态代理,所以Spring AOP 会这样子来进行切换:

  • 如果目标对象的实现类实现了接口,Spring AOP 将会采用 JDK 动态代理来生成 AOP 代理类;
  • 如果目标对象的实现类没有实现接口,Spring AOP 将会采用 CGLIB 来生成 AOP代理类——不过这个选择过程对开发者完全透明、开发者也无需关心。

使用XML配置AOP的步骤

spring中基于XML的AOP配置步骤
1、把通知Bean也交给spring来管理
2、使用aop:config标签表明开始AOP的配置
3、使用aop:aspect标签表明配置切面
id属性:是给切面提供一个唯一标识
ref属性:是指定通知类bean的Id。
4、在aop:aspect标签的内部使用对应标签来配置通知的类型

我们现在示例是让printLog方法在切入点方法执行之前之前:所以是前置通知
aop:before:表示配置前置通知
<aop:after-returning>: 配置后置通知,指定的增强方法在切入点方法正常执行之后执行.
<aop:after-throwing>: 配置异常通知,指定的增强方法在切入点方法产生异常后执行.
<aop:after>: 配置最终通知,无论切入点方法执行时是否发生异常,指定的增强方法都会最后执行.
<aop:around>: 配置环绕通知,可以在代码中手动控制增强代码的执行时机.
method属性:用于指定Logger类中哪个方法是前置通知
pointcut属性:用于指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强
切入点表达式
切入点表达式的写法
关键字:execution(表达式)
表达式:
访问修饰符 返回值 包名.包名.包名…类名.方法名(参数列表)
标准的表达式写法:
public void com.itheima.service.impl.AccountServiceImpl.saveAccount()
访问修饰符可以省略
void com.itheima.service.impl.AccountServiceImpl.saveAccount()
返回值可以使用通配符,表示任意返回值
* com.itheima.service.impl.AccountServiceImpl.saveAccount()
包名可以使用通配符,表示任意包。但是有几级包,就需要写几个*.
* *.*.*.*.AccountServiceImpl.saveAccount())
包名可以使用…表示当前包及其子包
* *..AccountServiceImpl.saveAccount()
类名和方法名都可以使用*来实现通配
* *..*.*()
参数列表:
可以直接写数据类型:
基本类型直接写名称 int
引用类型写包名.类名的方式 java.lang.String
可以使用通配符表示任意类型,但是必须有参数
可以使用…表示有无参数均可,有参数可以是任意类型
全通配写法:
* *..*.*(..)

实际开发中切入点表达式的通常写法是切到业务层实现类下的所有方法:
(重点)
* com.itheima.service.impl.*.*(..)

bean.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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

<!--配置spring的Ioc,把Service对象配置进来-->
	<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
    <!--配置logger通知类-->
	<bean id="logger" class="cn.itheima.utils.Logger"></bean>
	<!--配置AOP-->
    <aop:config>
        <!--配置切面 -->
        <aop:aspect id="logAdvice" ref="logger">
            <!--指定切入点表达式
             此标签写在aop:aspect标签内部只能当前切面使用。
              它还可以写在aop:aspect外面,此时就变成了所有切面可用-->
        <aop:pointcut expression="execution(* cn,itheima.service.impl.*.*(..))" id="pt1"></aop:pointcut>
            <!--配置各种类型的通知-->
        <aop:before method="printLogBefore" pointcut-ref="pt1"></aop:before>
        <aop:after-returning method="printLogAfterReturning" pointcut-ref="pt1"></aop:after-returning>
        <aop:after-throwing method="printLogAfterThrowing" pointcut-ref="pt1"></aop:after-throwing>
        <aop:after method="printLogAfter" pointcut-ref="pt1"></aop:after>
        </aop:aspect>
    </aop:config>
</beans>

环绕通知 (重点)

bean.xml

<!-- 配置环绕通知 详细的注释请看Logger类中-->
    <aop:around method="aroundPringLog" pointcut-ref="pt1"></aop:around>

Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。

它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。
logger类中

public Object aroundPringLog(ProceedingJoinPoint pjp){
        Object rtValue = null;
        try{
            Object[] args = pjp.getArgs();//得到方法执行所需的参数

            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置");

            rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)

            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置");

            return rtValue;
        }catch (Throwable t){
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常");
            throw new RuntimeException(t);
        }finally {
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终");
        }
    }

使用注解配置AOP

半注解配置AOP
半注解配置AOP,需要在bean.xml中加入下面语句开启对注解AOP的支持
(重点)

<?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"
       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/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

  <!-- 配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.itheima"></context:component-scan>

    <!-- 配置spring开启注解AOP的支持 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    </beans>

(重点)
@Aspect: 声明当前类为通知类,该类定义了一个切面.相当于xml配置中的<aop:aspect>标签

@Component("logger")
@Aspect//表示当前类是一个切面类
public class Logger {
		//...
}

用于声明通知的注解

@Before: 声明该方法为前置通知.相当于xml配置中的<aop:before>标签

@AfterReturning: 声明该方法为后置通知.相当于xml配置中的<aop:after- returning>标签

@AfterThrowing: 声明该方法为异常通知.相当于xml配置中的<aop:after-throwing>标签

@After: 声明该方法为最终通知.相当于xml配置中的<aop:after>标签

@Around (重点): 声明该方法为环绕通知.相当于xml配置中的<aop:around>标签

属性:
value: 用于指定切入点表达式或切入点表达式的引用

用于指定切入点表达式的注解(重点)

@Pointcut: 指定切入点表达式,其属性如下:

value: 指定表达式的内容
@Pointcut注解没有id属性,通过调用被注解的方法获取切入点表达式.

@Component("logger")
@Aspect//表示当前类是一个切面类
public class Logger {

    @Pointcut("execution(* com.itheima.service.impl.*.*(..))")
    private void pt1(){}

    /**
     * 前置通知
     */
    @Before("pt1()")
    public  void beforePrintLog(){
        System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。。。");
    }

    /**
     * 后置通知
     */
    @AfterReturning("pt1()")
    public  void afterReturningPrintLog(){
        System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了。。。");
    }
    /**
     * 异常通知
     */
    @AfterThrowing("pt1()")
    public  void afterThrowingPrintLog(){
        System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了。。。");
    }

    /**
     * 最终通知
     */
    @After("pt1()")
    public  void afterPrintLog(){
        System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了。。。");
    }
    @Around("pt1()")
    public Object aroundPringLog(ProceedingJoinPoint pjp){
        Object rtValue = null;
        try{
            Object[] args = pjp.getArgs();//得到方法执行所需的参数

            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置");

            rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)

            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置");

            return rtValue;
        }catch (Throwable t){
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常");
            throw new RuntimeException(t);
        }finally {
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终");
        }
    }
}

纯注解配置AOP

在Spring配置类前添加@EnableAspectJAutoProxy注解,可以使用纯注解方式配置AOP

@Configuration
@ComponentScan(basePackages="cn.maoritian")
@EnableAspectJAutoProxy			// 允许AOP
public class SpringConfiguration {
    // 具体配置
    //...
}
发布了33 篇原创文章 · 获赞 0 · 访问量 501

猜你喜欢

转载自blog.csdn.net/naerjiajia207/article/details/103467662
今日推荐