spring自定义注解AOP实现

时间:2022-05-13 20:37:16

基于spring boot 的aop pom配置:

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

首先定义注解:

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

public String name() default "";

}

然后在Controller层中定义测试方法:

    /**
* @comment 修改密码
* @author HE JIA
* @date 2017年7月6日 下午1:45:29
*/

@RequestMapping(value="updatePwd")
@ResponseBody
@TestAnnotation(name="张飞")
public Map<String,Object> updatePwd(String oldPwd,String newPwd){
return accountService.updatePwd(oldPwd,newPwd,request);
}

最后定义aop:

@Aspect
@Order(-99)
@Component
public class TestAspect {

@Before("@annotation(test)") //只过滤实现TestAnnotation注解的接口
public void beforeTest(JoinPoint point, TestAnnotation test) {
System.out.println("beforeTest:" + test.name());
}

@AfterReturning(value="@annotation(test)",returning="result") //方法返回值用result获取
public void afterTest(JoinPoint point, TestAnnotation test,Map<String,Object> result) {

System.out.println(result.get("state"));

System.out.println("afterTest:" + test.name());
}

}

最后打印:
beforeTest:张飞
error
afterTest:张飞