SpringAOP 注解方式实现

110 阅读2分钟

Spring 里需要学习的东西有很多,所以需要在实际工作中,包括私下里多去研究、验证,才能理解其中的意思,要不然很难去理解真正的含义。

比如 Spring Bean、 IOC、DI、AOP、声明式事务等等,很多,首先要知道怎么去运用,然后才是去看源码,学习源码的思想和实现思路。

今天就说下 Spring AOP 注解方式的实现,其实也很简单。就像造房子,我们要清楚造房子的步骤,从打地基,到砌墙,再到吊顶,装修等等。下面就是造一个名为 AOP 的房子的思路:

一、配置applicationContext.xml

<!-- 激活自动代理功能 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
<bean id="opeUserLogAspect" class="com.mxk.test.aop.opeUserLog.OpeUserLogAspect"></bean>

<import resource="classpath*:beans-*.xml" />
<import resource="classpath*:config/beans-*.xml" />
二、定义目标类接口

import java.lang.annotation.*;

@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface OpeUserLog {

/** 要执行的操作类型比如:add操作 **/
public String operationType() default "";

/** 要执行的具体操作比如:添加用户 **/
public String operationName() default "";

} 三、定义 SpringAOP 的 Aspect 类

import org.apache.log4j.Logger; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component;

@Aspect @Componnt public class OpeUserLogAspect {

private static final Logger logger = Logger.getLogger(OpeUserLogAspect.class);


// Controller层切点
@Pointcut("@annotation(com.mxk.test.aop.opeUserLog.OpeUserLog)")
public void opeUserLog() {
}

// 配置controller前置通知,使用在方法aspect()上注册的切入点
@SuppressWarnings("rawtypes")
@Before(value = "opeUserLog()")
public void around(JoinPoint joinPoint) {
    logger.info("==========开始执行controller前置通知===============");
    long start = System.currentTimeMillis();
    logger.info("==========结束执行controller前置通知===============");
    long end = System.currentTimeMillis();
    System.out.println("程序运行时间: "+(end - start)+"ms");
}

// 配置controller后置通知,使用在方法aspect()上注册的切入点
@SuppressWarnings("rawtypes")
@After(value = "opeUserLog()")
public void around(JoinPoint joinPoint) {
    logger.info("==========开始执行controller后置通知===============");
    long start = System.currentTimeMillis();
    logger.info("==========结束执行controller后置通知===============");
    long end = System.currentTimeMillis();
    System.out.println("程序运行时间: "+(end - start)+"ms");
}

// 配置controller环绕通知,使用在方法aspect()上注册的切入点
@SuppressWarnings("rawtypes")
@Around(value = "opeUserLog()")
public void around(JoinPoint joinPoint) {
    logger.info("==========开始执行controller环绕通知===============");
    long start = System.currentTimeMillis();
    logger.info("==========结束执行controller环绕通知===============");
    long end = System.currentTimeMillis();
    System.out.println("程序运行时间: "+(end - start)+"ms");
}

}

我是进阶的球儿,大家一起2019年的爬坑历程。感觉分享很给力的话给个赞,谢谢!!!有问题也可以下方留言或者加本人QQ:313989006 进行沟通。