有关什么是AOP,AOP能干什么,请自行百度。

我们采用自定义注解的方式,灵活使用AOP,总体步骤如下:

1.你既然要用人家AOP,总得加入依赖吧,在项目的pom.xml加入

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

2.自定义注解,你总得自己搞一个注解,不过分吧

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface needAuth {
    String value() default "";
}

3.创建你使用AOP要做的事情--通知,比如权限控制啊,调用方法需要自定义的日志服务啊什么的

@Component
@Aspect
public class LogAspect {

//    @Pointcut("execution(* com.csj.springdemo.controller..*(..))")
    @Pointcut("@annotation(com.csj.springdemo.annotation.needAuth)")
    public void logPoint(){//这就是个标志,爱叫啥叫啥,给下面用的
    }

    @Before("logPoint()")
    public void beforeAop(){
        System.out.println("前置通知...");
    }
    @After("logPoint()")
    public void afterAop(){
        System.out.println("后置通知...");
    }
    @Around("logPoint()")
    public void aroundAop(ProceedingJoinPoint pj) throws Throwable {
        System.out.println("环绕通知前...");
        pj.proceed();//这个有点东西,几个注解的执行顺序有关
        System.out.println("环绕通知后...");
    }
}

@Aspect注解不能少了

4.最后一步就是用了

为了验证测试,自己加个Controller类,再加个Service层就行了,简单点

@RestController
@RequestMapping("/aop")
public class SpringAopTestController {
    @Autowired
    SpringAopTestService springAopTestService;

    @RequestMapping("/test")
    public void aopTest(){
        springAopTestService.message();
    }
    @RequestMapping("/anoMessage")
    public void anoMessage(){
        springAopTestService.anoMessage();
    }
}
@Service
public class SpringAopTestService {

    public void message(){
        System.out.println("执行方法message");
    }

    @needAuth()
    public void anoMessage(){
        System.out.println("执行方法needAuth");
    }
}

用postman测下就可以了

第一个是执行没使用注解的结果 /aop/test

 第二个是执行使用注解的结果 /aop/anoMessage

是不是炒鸡简单,当然,还有很多花样玩法,那就得再学学了,一步步来,别望而止步了。 

另,除了使用注解的方式,还有可以用execution表达式【具体自行百度,很简单】,让这个类下的方法都具备AOP的功能,不需要在每个方法都加上注解了,各有用处,看实际需求。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐