当前位置: 代码迷 >> 综合 >> Spring -> AOP增强方法(Before,After,AfterThrowing,AfterReturning)
  详细解决方案

Spring -> AOP增强方法(Before,After,AfterThrowing,AfterReturning)

热度:34   发布时间:2023-12-16 10:01:05.0

1.被代理的类

public interface Aop {
    void add();
}
@Component("aopImplement")
public class AopImplement implements Aop{
    @Overridepublic void add() {
    System.out.println("我是add已经存在的功能");}
}

2.代理类(Before,After,AfterThrowing,AfterReturning,Around)

@Component
@Aspect
public class AopAddClass {
    //方法之前@Before("execution(* test10month.test1014.AopImplement.add(..))")public void beFore() {
    System.out.println("我是before");}//方法之后@After("execution(* test10month.test1014.AopImplement.add(..))")public void after() {
    System.out.println("我是after");}//方法出现异常时@AfterThrowing("execution(* test10month.test1014.AopImplement.add(..))")public void afterThrowing() {
    System.out.println("我是afterThrowing");}//方法返回retuen时@AfterReturning("execution(* test10month.test1014.AopImplement.add(..))")public void afterReturning() {
    System.out.println("我是afterReturning");}//围绕整个方法在before之前和after之后@Around("execution(* test10month.test1014.AopImplement.add(..))")public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    System.out.println("我是around前");//需要调用proceedingjoinpoint的proceed方法才会继续执行方法的调用//否则在围绕这里就中断,不会继续执行方法proceedingJoinPoint.proceed();System.out.println("我是around后");}
}

3.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd"><context:component-scan base-package="test10month.test1014"/><!--proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。如果proxy-target-class 属性值被设置为true,那么基于类的代理将起作用(这时需要cglib库)。如果proxy-target-class属值被设置为false或者这个属性被省略,那么标准的JDK 基于接口的代理将起作用。--><aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>

4.测试类

public class Test1014 {
    public static void main(String[] args) {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test10month/test1014/AOP.xml");AopImplement bean = context.getBean("aopImplement", AopImplement.class);bean.add();/** * 我是Around前* 我是Before* 我是add已经存在的功能* 我是AfterReturning* 我是After* 我是Around后*/ }
}
  相关解决方案