Spring boot 自定義註解
相信很多學習Spring框架初學者都會碰到各種註解比如@Controller , @Response,@Compent等各類註解,如何在Spring boot中增加自己的註解,是一個比較基礎的話題,也是進入AOP程式設計大門必經之路。
首先定義一個@Annotation的註解介面如下:
package com.AnnotationTest;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SelfAnnotation {
String desc() default "Hi Call";
}
第二部定義切面
package com.AnnotationTest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class Logging {
@Pointcut("@annotation(com.AnnotationTest.SelfAnnotation)")
private void cut(){}
@Before("cut()")
public void BeforeCall()
{
System.out.println("事前通知");
}
@Around("cut()")
public void AroundCall(ProceedingJoinPoint joinPoint)
{
System.out.println("環繞通知之開始");
try {
joinPoint.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("環繞通知之結束");
}
@After("cut()")
public void AfterCall()
{
System.out.println("事後通知");
}
}
第三部定義一個控制器,
package com.AnnotationTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
//@Scheduled(fixedRate=5000)
void TimeCall()
{
callMyRoute();
}
@RequestMapping("/index")
public String index() {
runner.Run();
return "this is my index";
}
/*
@SelfAnnotation
public void callMyRoute()
{
System.out.println("MyController is callMyRoute");
}*/
@Autowired
private TestRunner runner;
}
大家注意到紅色部分字型,程式碼,這部分如果使用,使用自定義註解,這個切面是否能生效。
第四部 我們再定義一個註解使用類
package com.AnnotationTest;
import org.springframework.stereotype.Service;
@Service
public class TestRunner {
@SelfAnnotation
public void Run()
{
System.out.println("MyController is Run");
}
}
第五步定義主函式使用Spring boot 啟動程式
package com.AnnotationTest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SelfAnnotationTestApplication {
public static void main(String[] args) {
SpringApplication.run(SelfAnnotationTestApplication.class, args);
}
}
執行結果可以
環繞通知之開始
事前通知
MyController is Run
環繞通知之結束
事後通知
但是,其實控制器中定時任務中註解並沒有生效。