欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot:aop 博客分类: springboot springbootaop 

程序员文章站 2024-02-13 16:52:04
...
===================================================
application.properties 增加aop选项
===================================================
# AOP
spring.aop.auto=true
spring.aop.proxy-target-class=true

如果proxy-target-class 属性值被设置为true,那么基于类的代理将起作用(这时需要cglib库)。
如果proxy-target-class属值被设置为false或者这个属性被省略,那么标准的JDK 基于接口的代理。
如果不给出 proxy-target-class,就按 proxy-target-class=“false”对待,也即是按JDK proxy来处理的。
===================================================
AopTest.java

<bean id="logService" class="org.spring.springboot.aop.AopTest"/>
    <aop:config>
        <aop:aspect id="log" ref="logService">
            <aop:pointcut expression="execution(public * org.spring.springboot.web..*.*(..))" id="cLog"/>
            <aop:before method="around" pointcut-ref="cLog"/>
            <aop:before method="before" pointcut-ref="cLog"/>
            <aop:after method="after" pointcut-ref="cLog"/>
            <aop:after-returning method="doAfterReturning" pointcut-ref="cLog" returning="object"/>
            <aop:after-throwing method="doAfterThrowing" pointcut-ref="cLog" arg-names="joinpoint,exception"
                                throwing="exception"/>
        </aop:aspect>
    </aop:config>

===================================================
@Aspect
@Component
public class AopTest {

    @Pointcut("execution(public * org.spring.springboot.web..*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void before(JoinPoint joinpoint) {

        // 此方法返回的是一个数组,数组中包括request以及ActionCofig等类对象
        Object[] args = joinpoint.getArgs();

        if (args != null && args.length > 0) {

            if (args[0] instanceof HttpServletRequest) {
                HttpServletRequest request = (HttpServletRequest) args[0];
                System.out.println("Request URI: " + request.getRequestURI());
            }
        }
    }

    @After("webLog()")
    public void after(JoinPoint joinpoint) {
        System.out.println("joinpoint = [" + joinpoint + "]");
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        System.out.println("ret = [" + ret + "]");
    }

    @AfterThrowing(pointcut = "webLog()", argNames = "joinpoint,exception", throwing = "exception")
    public void doAfterThrowing(JoinPoint joinpoint, Exception exception) {

        String className = joinpoint.getTarget().getClass().getName();// 类名
        String methodName = joinpoint.getSignature().getName();// 方法名字

        String content = "--------------------------------reqlog. Exception error class "
                + className
                + "_"
                + methodName
                + "====== message ======"
                + exception.getMessage();
        System.out.println(content);
        System.out.println(exception);
    }

}
相关标签: springboot aop