【java自定義註解2】java自定義註解結合Spring AOP
阿新 • • 發佈:2018-11-26
承接上一篇,註解應用於屬性,本篇定義了一個用於方法的註解,結合Spring AOP 實現 切面程式設計。
以下demo演示使用了SpringBoot,與SSM中使用方式大致相同,效果如下:
1、自定義註解(用於方法)
/** * 自定義註解 * @author Zx * */ @Target(ElementType.METHOD)//作用於方法 @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MethodAonn { //註解屬性 String name() default "";; String prot() default "";; String value() default "預設值"; }
2、自定義Controller,使用自定義註解
/** * 測試用控制器 */ @RestController @RequestMapping("asp") public class WorkController { @RequestMapping("/exec") //使用自定義註解 @MethodAonn(name = "註解name屬性") public void extcute() { System.out.println("extcute()方法執行"); }; @RequestMapping("/stop") @MethodAonn(name = "被註解方法開始執行") public void stop() { System.out.println("stop()方法執行"); }; }
3、建立切面
@Aspect // 註解宣告一個切面 @Component // 受spring管理的容器 public class MethodAspect { @Pointcut("@annotation(com.xxx.ann.simple2.MethodAonn)") // 註解宣告切點,註解的全限定名 public void annotationPointcut() { }; @After("annotationPointcut()") public void after(JoinPoint joinPoint) { MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature(); Method method = methodSignature.getMethod(); String name = method.getName(); MethodAonn annotation = method.getAnnotation(MethodAonn.class); System.out.println("攔截 : " + name+"方法執行"); System.out.println(">>>: " + annotation.name()); } }
4、啟動類啟動容器
@SpringBootApplication
@Configuration //註冊被spring管理
@EnableAspectJAutoProxy //註解開啟對aspectJ的支援
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
5、啟動後通過req訪問測試:
http://localhost:8080/asp/exec
6、攔截結果:
extcute()方法執行
攔截 : extcute方法執行
>>>: 註解name屬性