首先先检查自己是否添加了依赖,这个贼坑
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
其次 boot启动类添加 aspect 自动代理以及包的扫描
@SpringBootApplication
@ComponentScan("com.example.demo.*")
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Target(value = ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
public @interface syslog {
}
@Aspect
@Component
@Slf4j
public class SysAspect {
@Pointcut("@annotation(com.example.demo.utils.commons.syslog)")
public void cutPoint(){}
@AfterReturning("cutPoint()")
public void sysNotic(JoinPoint joinPoint){
log.info("呜呜呜呜呜呜呜"+joinPoint.toString());
System.out.println("后");
}
}
@syslog
@RequestMapping(value = "/controller",method = RequestMethod.GET)
public int controller() throws NoSuchFieldException {
System.out.println("进入方法了!");
return 1;
}
最后打印结果
进入方法了!
2019-09-20 15:18:13.409 INFO 8064 --- [nio-8080-exec-1] c.example.demo.utils.commons.SysAspect : 呜呜呜呜呜呜呜execution(int com.example.demo.controller.diyAnnotationController.controller())
后