Spring详解(七)------AOP 注解

 

1、注解实现 AOP

①、导入相应的 jar 包,以及在 applicationContext.xml 文件中导入相应的命名空间。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">   
     
</beans>

 ②、注解配置 bean

<!--1、创建目标类 -->
<bean id="userService" class="com.ys.aop.UserServiceImpl"></bean>  
<!--2、创建切面类(通知)  -->
<bean id="myAspect" class="com.ys.aop.MyAspect"></bean>

目标类:

切面类:

③、配置扫描注解识别

  这个我们在前面也讲过,上面配置的注解,Spring 如何才能识别这些类上添加了注解呢?我们必须告诉他。

  在 applicationContext.xml 文件中添加如下配置:

<!-- 配置扫描注解类
        base-package:表示含有注解类的包名。
        如果扫描多个包,则下面的代码书写多行,改变 base-package 里面的内容即可!
    -->
    <context:component-scan base-package="com.ys.aop"></context:component-scan>

④、注解配置 AOP

一、我们用xml配置过如下:

  

  这是告诉 Spring 哪个是切面类。下面我们用注解配置

  我们在切面类上添加 @Aspect 注解,如下:

  

 二、如何让 Spring 认识我们所配置的 AOP 注解呢?光有前面的类注解扫描是不够的,这里我们要额外配置 AOP 注解识别。

  我们在 applicationContext.xml 文件中增加如下配置:

<!--2、确定 aop 注解生效  -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

  如果是没有配置文件而是配置累:给配置类中加 @EnableAspectJAutoProxy 【开启基于注解的aop模式】

三、注解配置前置通知

<!-- 切入点表达式 -->
        <aop:pointcut expression="execution(* com.ys.aop.*.*(..))" id="myPointCut"/>
        <!-- 3.1 前置通知
                <aop:before method="" pointcut="" pointcut-ref=""/>
                    method : 通知,及方法名
                    pointcut :切入点表达式,此表达式只能当前通知使用。
                    pointcut-ref : 切入点引用,可以与其他通知共享切入点。
                通知方法格式:public void myBefore(JoinPoint joinPoint){
                    参数1:org.aspectj.lang.JoinPoint  用于描述连接点(目标方法),获得目标方法名等
        -->
        <aop:before method="myBefore" pointcut-ref="myPointCut"/>

3、注解改进  

我们可以看前置通知和后置通知的注解配置:

4、总结 

   上面我们只进行了前置通知和后置通知的讲解,还有比如最终通知、环绕通知、抛出异常通知等,配置方式都差不多,这里就不进行一一讲解了。然后我们看一下这些通知的注解:

  @Aspect  声明切面,修饰切面类,从而获得 通知。

  通知

    @Before 前置

    @AfterReturning 后置

    @Around 环绕

    @AfterThrowing 抛出异常

    @After 最终

给方法上标注 @Transactional 表示当前方法是一个事务方法;
@EnableTransactionManagement 开启基于注解的事务管理功能;

原文地址:https://www.cnblogs.com/deityjian/p/11067503.html