手写SpringBoot(五)之整合AOP
Spring开启aop只需要在任意一个加了@Configuration配置类的上面加上@EnableAspectJAutoProxy
注解就行
新建my-spring-boot-starter-aop模块
- 引入aspectj依赖
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.5</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.9.5</version> </dependency> <dependency> <groupId>cn.axj</groupId> <artifactId>my-spring-boot-configuration</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
- 创建AopAutoConfiguration配置类,并配置@EnableAspectJAutoProxy注解
package cn.axj.aop.springboot.config; import cn.axj.springboot.my.config.AutoConfiguration; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration public class AopAutoConfiguration implements AutoConfiguration { @Configuration @EnableAspectJAutoProxy static class AspectjConfiguration{ } }
- 创建配置类文件 META-INF/service/cn.axj.springboot.my.config.AutoConfiguration文件,并将AopAutoConfiguration的路径配置进去
cn.axj.aop.springboot.config.AopAutoConfiguration
下面开始测试,在user-servcie模块中引入my-spring-boot-starter-aop
<dependency> <groupId>cn.axj</groupId> <artifactId>my-spring-boot-starter-aop</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
- 创建aop包,并创建TestAopAnnotation注解
package cn.axj.user.aop; import java.lang.annotation.*; @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface TestAopAnnotation { }
- 创建aop代理类TestAop
package cn.axj.user.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; @Aspect @Component public class TestAop { @Around("@annotation(cn.axj.user.aop.TestAopAnnotation)") public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { Object proceed = proceedingJoinPoint.proceed(); String after = "after advice"; return after + "____" + proceed; } }
- 在TestController ,test方法上面加上注解@TestAopAnnotation
@GetMapping(value = "/test") @TestAopAnnotation public String test(Integer id){ return userService.test(id).toString(); }
开启user-service模块
访问localhost:8080/test?id=2
返回
after advice____User{id=2, username='lisi'},看到返回aop代理字符串after advice____,aop开启成功