Spring Boot - AOP

作者: yuanzicheng | 来源:发表于2018-04-09 15:27 被阅读37次

Spring Boot中使用AOP无需任何配置,仅需添加AOP相关依赖就可以开始使用了。

compile('org.springframework.boot:spring-boot-starter-aop:2.0.0.RELEASE')

以注解方式结合AOP实现MongoDB自动存储为例介绍AOP在Spring Boot中的使用。

Step 1:自定义注解

import java.lang.annotation.*;

/**
 * 自定义注解,结合AOP实现MongoDB自动缓存
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
@Documented
public @interface MongoCache {
}

Step 2:使用@Aspect注解定义

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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MongoAspect {

    private Logger logger = LoggerFactory.getLogger(MongoAspect.class);

    @Pointcut(value = "@annotation(your.package.MongoCache)")
    public void setJoinPoint(){}

    //环绕通知:可以获取返回值
    @Around(value = "setJoinPoint()")
    public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint){
        Object result = null;
        try {
            //前置通知
            result = proceedingJoinPoint.proceed();
            //返回通知
            //存储至MongoDB
            Object[] args = proceedingJoinPoint.getArgs();
            logger.info("存储至MongoDB...");
        } catch (Throwable e) {
            //异常通知
            logger.error(e.getLocalizedMessage(),e);
        }
        //后置通知
        return result;
    }
}

Step 3:在需要的方法上添加自定义注解

@RestController
public class HelloController {
    @MongoCache
    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }
}

简单几步就能通过自定义注解实现AOP处理了,当然示例中还有些细节没有展开(如:存储至MongoDB的内容)。

相关文章

网友评论

    本文标题:Spring Boot - AOP

    本文链接:https://www.haomeiwen.com/subject/svxllxtx.html