纯笔记
注解:MyAnnotation
package com.example.demo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
int p0() default 0;
String p1() default "";
}
AOP:MyAspect
package com.example.demo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect
@Component
public class MyAspect {
@Around(value = "@annotation(com.example.demo.MyAnnotation)")
public Object aroundExec(ProceedingJoinPoint pjp) throws Throwable {
MethodSignature ms = (MethodSignature) pjp.getSignature();
Method method = ms.getMethod();
MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
System.out.println(myAnnotation.p0());// 参数p0的值
System.out.println(myAnnotation.p1());// 参数p1的值
return pjp.proceed();
}
}
demo:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class DemoApplication {
@MyAnnotation(p0 = 123, p1 = "ywj")
@GetMapping("/hello")
public Object hello(){
return 0;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
result:
2019-06-26 20:35:45.236 INFO 2840 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-06-26 20:35:45.734 INFO 2840 --- [ main] org.xnio : XNIO version 3.3.8.Final
2019-06-26 20:35:45.745 INFO 2840 --- [ main] org.xnio.nio : XNIO NIO Implementation Version 3.3.8.Final
2019-06-26 20:35:45.812 INFO 2840 --- [ main] o.s.b.w.e.u.UndertowServletWebServer : Undertow started on port(s) 8080 (http) with context path ''
2019-06-26 20:35:45.815 INFO 2840 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 2.592 seconds (JVM running for 3.361)
2019-06-26 20:35:47.635 INFO 2840 --- [ XNIO-1 task-1] io.undertow.servlet : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-06-26 20:35:47.635 INFO 2840 --- [ XNIO-1 task-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-06-26 20:35:47.642 INFO 2840 --- [ XNIO-1 task-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 7 ms
123
ywj