8.spring中的AOP

转载:https://blog.kuangstudy.com/index.php/archives/533/

一.AOP

1.什么是AOP

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

2.AOP在spring中的作用

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

  • 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 ....

  • 切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。

  • 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。

  • 目标(Target):被通知对象。

  • 代理(Proxy):向目标对象应用通知之后创建的对象。

  • 切入点(PointCut):切面通知 执行的 “地点”的定义。

  • 连接点(JointPoint):与切入点匹配的执行点。

 

 

 

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

 

  • AOP在不改变原有的代码情况下,去增加了新的功能。

3.spring实现AOP的三种写法

  1. 使用spring的API

  2. 自定义API

  3. 使用注解

(1)导AOP的jar包

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

(2)配置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"
    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>

(3)使用spring的API实现AOP

步骤:

  1. 业务接口和业务实体类:UserService,UserServiceImpl

  2. 切入类:BeforeLog,AfterLog

  3. 配置文件:applicationContext.xml

  4. 测试类:MyTest

业务接口和业务实体类:UserService,UserServiceImpl

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

切入类:BeforeLog,AfterLog

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

配置文件:applicationContext.xml

说明:

  1. 需要配置 xmlns:aop="http://www.springframework.org/schema/aop" 和 http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop.xsd 

  2. 切入点 <aop:pointcut id="pointcut" expression="execution(* ustc.wzh.service.UserServiceImpl.*(..))"/>

    1. id属性为自定义的切入点名称
    2. expression属性值为需要切入的方法: 返回值类型  包名.类名.方法名(参数类型)  
    3. execution(* ustc.wzh.service.UserServiceImpl.*(..)) 表示返回值任意的ustc.wzh.service.UserServiceImpl类的任意方法和任意参数
  3. 通知 <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/> 

    1.  advice-ref="beforeLog" 使用某个实体类,该实体类已经实现了Adivce接口

    2.  pointcut-ref="pointcut" 指定切入的切入点

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

测试类:MyTest

1 public class MyTest {
2     @Test
3     public void test(){
4         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
5         UserService userService = (UserService) context.getBean("userService");
6         userService.search();
7     }
8 }

(4)自定义API实现AOP

步骤:

  1. 业务接口和业务实体类:UserService,UserServiceImpl(已有)

  2. 切入类:DiyPointcut

  3. 配置文件:applicationContext.xml

  4. 测试类:MyTest(已有)

切入类:DiyPointcut

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

配置文件:applicationContext.xml

说明:

  1. 切面 <aop:aspect ref="diy"> ,在spring API中使用的是切入点,自定义则使用切面用于直接放入一个类而不是方法了,放入了 ustc.wzh.diy.DiyPointcut 类

  2.  <aop:before pointcut-ref="diyPonitcut" method="before"/>  <aop:after pointcut-ref="diyPonitcut" method="after"/> 绑定类的方法

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

(5)使用注解实现AOP

步骤:

  1. 业务接口和业务实体类:UserService,UserServiceImpl(已有)

  2. 切入类:AnnotationPointcut

  3. 配置文件:applicationContext.xml

  4. 测试类:MyTest(已有)

切入类:AnnotationPointcut

说明:

  1. @Aspect:表示切面,需要切入的类

  2.  @Before("execution(* ustc.wzh.service.UserServiceImpl.*(..))") :表示在方法执行前切入以及哪些方法需要切入

 1 import org.aspectj.lang.ProceedingJoinPoint;
 2 import org.aspectj.lang.annotation.After;
 3 import org.aspectj.lang.annotation.Around;
 4 import org.aspectj.lang.annotation.Aspect;
 5 import org.aspectj.lang.annotation.Before;
 6 
 7 @Aspect
 8 public class AnnotationPointcut {
 9     @Before("execution(* ustc.wzh.service.UserServiceImpl.*(..))")
10     public void before(){
11         System.out.println("---------方法执行前---------");
12     }
13 
14     @After("execution(* ustc.wzh.service.UserServiceImpl.*(..))")
15     public void after(){
16         System.out.println("---------方法执行后---------");
17     }
18 
19     @Around("execution(* ustc.wzh.service.UserServiceImpl.*(..))")
20     public void around(ProceedingJoinPoint jp) throws Throwable {
21         System.out.println("环绕前");
22         System.out.println("签名:"+jp.getSignature());
23         //执行目标方法proceed
24         Object proceed = jp.proceed();
25         System.out.println("环绕后");
26         System.out.println(proceed);
27     }
28 }

配置文件:applicationContext.xml

说明:

  1.  <aop:aspectj-autoproxy/> :开启AOP注解

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

补充:

  • 通过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动态代理。

 

posted @ 2020-02-18 18:09  All_just_for_fun  阅读(263)  评论(0编辑  收藏  举报