Spring AOP实现

124 阅读2分钟

AOP是面向切面

  • OOP的延续,主要应用在日志切面、事务控制切面、权限控制切面、异步切面和缓存切面,利用AOP可以对任务解耦,通过重用性,提升效率。

AOP 术语

AOP 领域中的特性术语:

  • 通知(Advice): AOP 框架中的增强处理。通知描述了切面何时执行以及如何执行增强处理。
  • 连接点(join point): 连接点表示应用执行过程中能够插入切面的一个点,这个点可以是方法的调用、异常的抛出。在 Spring AOP 中,连接点总是方法的调用。
  • 切点(PointCut): 可以插入增强处理的连接点。
  • 切面(Aspect): 切面是通知和切点的结合。
  • 引入(Introduction):引入允许我们向现有的类添加新的方法或者属性。
  • 织入(Weaving): 将增强处理添加到目标对象中,并创建一个被增强的对象,这个过程就是织入。

概念看起来总是有点懵,并且上述术语,不同的参考书籍上翻译还不一样,所以需要慢慢在应用中理解。

其实就是和动态代理中的invoke方法差不多

image.png 先引入maven依赖

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

在beans.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"
       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">
</beans>

实现方式一

使用Spring API(接口) AfterReturningAdviceMethodBeforeAdvice

接口

public interface UserService {
    void add();
    void delete();
    void update();
    void select();
}

实现接口(真实对象)

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 select() {
        System.out.println("查询");
    }
}

实现AOP的API
AfterReturningAdvice

public class LogAfter implements AfterReturningAdvice  {
    @Override
    public void afterReturning(Object retValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("执行了"+method.getName()+",返回结果为:"+retValue);
    }
}

MethodBeforeAdvice

public class LogBefore implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] arg, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}

配置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">
    <bean id="userService" class="com.spring.service.UserServiceImpl"/>
    <bean id="after" class="com.spring.log.LogAfter"/>
    <bean id="before" class="com.spring.log.LogBefore"/>
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.spring.service.UserServiceImpl.*(..))"/>
        <aop:advisor advice-ref="before" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="after" pointcut-ref="pointcut"/>
    </aop:config>
</beans>

expression="execution(* com.spring.service.UserServiceImpl.*(..))
execution(* * * * *)

  • 第一个* 表示任意返回值类型
  • 第二个* 表示以任意名字开头的package. 如 com.xx.
  • 第三个* 表示以任意名字开头的class的类名 如TestService
  • 第四个* 表示 通配 *service下的任意class
  • 最后二个(..) 表示通配 方法可以有0个或多个参数

test

getBean的是接口

public class MyTest {
    @Test
    public void test01(){
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        UserService userService = context.getBean("userService",UserService.class);//代理的是接口
        userService.add();
    }
}

image.png

image.png

image.png

方式二

自定义(切面)

样例
在方式一的基础上进行更改
新建一个类

public class DiyPointCut {
    public void before(){
        System.out.println("Before.....");
    }
    public void after(){
        System.out.println("After.....");
    }
}

更改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">
    <bean id="userService" class="com.spring.service.UserServiceImpl"/>
    <bean id="diy" class="com.spring.diyPointcut.DiyPointCut"/>
    <aop:config>
        <aop:aspect ref="diy">
            <aop:pointcut id="pointcut" expression="execution(* com.spring.service.UserServiceImpl.*(..))"/>
            <aop:before method="before"  pointcut-ref="pointcut"/>
            <aop:after method="after" pointcut-ref="pointcut"/>
        </aop:aspect> 
    </aop:config>
</beans>

其他不变

image.png

方式三(注解)

增强类

@Aspect
public class Annotation {
    @Before("execution(* com.spring.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("Annotation Before....");
    }
    @After("execution(* com.spring.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("Annotation After....");
    }
    public void aroundBefore(){
        System.out.println("aroundBefore");
    }
    public void aroundAfter(){
        System.out.println("aroundBefore");
    }
    @Around("execution(* com.spring.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
          aroundBefore();
          joinPoint.proceed();//切入点
          aroundAfter();
    }
}

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">
    <bean id="userService" class="com.spring.service.UserServiceImpl"/>
    <bean id="annotation" class="com.spring.annotation.Annotation"/><!--注册增强类-->
    <aop:aspectj-autoproxy/><!--开启注解支持-->
</beans>

image.png