SpringBoot使用AOP

题目要求

SpringBoot使用AOP

实现例子

创建好boot项目导入aop依赖

        <!--导入AOP-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
    </dependencies>

编写好变形金刚实现类

package com.jie.service;

import org.springframework.stereotype.Service;

@Service
public class TransformersImpl implements Transformers {
    @Override
    public void attack() {
        System.out.println("进行攻击");
    }

    @Override
    public void errorTest() {
        int i=1/0;
    }

    @Override
    public String aroundTest() {
        System.out.println("方法正常运行");
        return "hello";
    }
}

编写Aspect类

package com.jie.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class TransformersAspect {
    //匹配com.jie.pojo包及其子包下的所有类的所有方法
    @Pointcut("execution(* com.jie.service.TransformersImpl.attack(..))")
    public void pointCut(){

    }
    @Before("pointCut()")
    public void beforeAdvice(JoinPoint joinPoint){
        System.out.println("前置方法执行---");
        System.out.println("准备挥拳");
    }
    @After("pointCut()")
    public void afterAdvice(JoinPoint joinPoint){
        System.out.println("后置方法执行---");
        System.out.println("攻击结束");
    }
    @AfterThrowing(value = "execution(* com.jie.service.TransformersImpl.errorTest(..))", throwing = "e")
    public void afterThrowingAdvice(JoinPoint joinPoint,Exception e){
        System.out.println("出现异常");
        System.out.println(e.getMessage());
    }
    @Around("execution(* com.jie.service.TransformersImpl.aroundTest(..))")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint){
        System.out.println("环绕前置通知---");
        System.out.println("环绕通知的目标方法名:"+proceedingJoinPoint.getSignature().getName());
        try{
            //执行方法
            Object proceed = proceedingJoinPoint.proceed();
            return proceed;
        }
        catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        finally {
            System.out.println("环绕后置通知");
        }
        return null;
    }
}

注意要使用@Aspect注解
之后就可以愉快的使用了

@SpringBootTest
class Day08AopmybatisApplicationTests {
    @Autowired
    TransformersImpl transformers;
    @Test
    void contextLoads() {
        transformers.attack();
    }
    @Test
    void test2(){
        transformers.errorTest();
    }
    @Test
    void test3(){
        System.out.println(transformers.aroundTest());
    }
}
上一篇:Python 循环结构练习


下一篇:Html中url的编码和解码