Implements custom annotations through interceptor AOP, where the interceptor acts as a method to be executed at the specified annotation , AOP is responsible for weaving the interceptor method and the place where the annotation takes effect (generating proxy class implementation through dynamic annotation).
spring-boot-starter: Some core basic dependencies of spring
spring-boot-starter-aop: Some related dependencies of spring to implement Aop
org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-aop
1. Custom annotation class
@Target({ElementType.TYPE}) //说明了Annotation所修饰的对象范围,这里,的作用范围是类、接口(包括注解类型) 或enum @Retention(RetentionPolicy.RUNTIME) //自定义注解的有效期,Runtime:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在 @Documented //标注生成javadoc的时候是否会被记录 public @interface EasyExceptionResult { }
2.Interceptor class
/** * MethodInterceptor是AOP项目中的拦截器(注:不是动态代理拦截器), * 区别与HandlerInterceptor拦截目标时请求,它拦截的目标是方法。 */ public class EasyExceptionIntercepter implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { AnnotatedElement element=invocation.getThis().getClass(); EasyExceptionResult easyExceptionResult=element.getAnnotation(EasyExceptionResult.class); if (easyExceptionResult == null) { return invocation.proceed(); } try { return invocation.proceed(); } catch (Exception rpcException) { //不同环境下的一个异常处理 System.out.println("发生异常了"); return null; } } }
3. Pointcut aspect class
The implementation class of MethodInterceptor can be used as the execution method of the aspect because the parent class of Interceptor is Advice.
@Configuration public class EasyExceptionAdvisor { /** * 放在最后执行 * 等待ump/日志等记录结束 * * @return {@link DefaultPointcutAdvisor}对象 */ @Bean @Order(Integer.MIN_VALUE) public DefaultPointcutAdvisor easyExceptionResultAdvisor() { DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(); //针对EasyExceptionResult注解创建切点 AnnotationMatchingPointcut annotationMatchingPointcut = new AnnotationMatchingPointcut(EasyExceptionResult.class, true); EasyExceptionIntercepter interceptor = new EasyExceptionIntercepter(); advisor.setPointcut(annotationMatchingPointcut); //在切点执行interceptor中的invoke方法 advisor.setAdvice(interceptor); return advisor; } }
4. Use of custom annotations
@Service @EasyExceptionResult //自定义异常捕获注解 public class EasyServiceImpl { public void testEasyResult(){ throw new NullPointerException("测试自定义注解"); } }
5. Effect
@SpringBootApplication public class JdStudyApplication { public static void main(String[] args) { ConfigurableApplicationContext context=SpringApplication.run(JdStudyApplication.class, args); EasyServiceImpl easyService=context.getBean(EasyServiceImpl.class); easyService.testEasyResult(); } }
So far, custom annotations have been implemented through spring.
Although custom annotations are implemented through Spring, there are still ways for us to implement custom annotations without using Spring. After all, annotations are earlier than Spring.
There are some meta-annotations in JDK, mainly @Target, @Retention, @Document, and @Inherited, which are used to modify annotations. The following is a custom annotation.
@Target({ElementType.TYPE}) //说明了Annotation所修饰的对象范围,这里,的作用范围是类、接口(包括注解类型) 或enum @Retention(RetentionPolicy.RUNTIME) //自定义注解的有效期,Runtime:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在 @Documented //标注生成javadoc的时候是否会被记录 public @interface EasyExceptionResult { }
@Target
Indicates the java element type to which this annotation can be applied
Target type | Description |
---|---|
ElementType.TYPE | Applies to classes, interfaces (including annotation types), and enumerations |
ElementType.FIELD | Applies to properties (including constants in enumerations) |
ElementType.METHOD | Applies to methods |
ElementType.PARAMETER | Formal parameters applied to methods |
ElementType.CONSTRUCTOR | Applied to constructors |
ElementType.LOCAL_VARIABLE | Apply to local variables |
ElementType.ANNOTATION_TYPE | Apply to annotation types |
ElementType.PACKAGE | Apply to package |
ElementType.TYPE_PARAMETER | New in version 1.8, applied to type variables ) |
ElementType.TYPE_USE | New in version 1.8, it applies to any statement that uses types (such as types in declaration statements, generics, and cast statements) |
@Retention
Indicates the life cycle of the annotation
Lifecycle type | Description |
---|---|
RetentionPolicy.SOURCE | Discarded at compile time and not included in the class file |
RetentionPolicy.CLASS | Discarded when the JVM loads, included in the class file, the default value |
RetentionPolicy.RUNTIME | is determined by the JVM Loaded, included in the class file, and can be obtained at runtime |
@Document
indicates the element marked by the annotation Can be documented by Javadoc or similar tools
@Inherited
An annotation that indicates the use of the @Inherited annotation. Subclasses of the marked class will also have this annotation
After we define the annotations, we need to consider how to bind the annotations and classes together to achieve the effect we want during runtime. Here we can introduce dynamic proxies The mechanism of the annotation is to perform a weaving operation when the class is compiled before the method is executed, as follows.
public static void main(String[] args) { Class easyServiceImplClass=EasyServiceImpl.class; //判断该对象是否有我们自定义的@EasyExceptionResult注解 if(easyServiceImplClass.isAnnotationPresent(EasyExceptionResult.class)){ final EasyServiceImpl easyService=new EasyServiceImpl(); //cglib的字节码加强器 Enhancer enhancer=new Enhancer(); 将目标对象所在的类作为Enhaner类的父类 enhancer.setSuperclass(EasyServiceImpl.class); 通过实现MethodInterceptor实现方法回调,MethodInterceptor继承了Callback enhancer.setCallback(new MethodInterceptor() { @Override public Object intercept(Object proxy, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { try{ method.invoke(easyService, args); System.out.println("事务结束..."); }catch (Exception e){ System.out.println("发生异常了"); } return proxy; } }); Object obj= enhancer.create();; EasyServiceImpl easyServiceProxy=(EasyServiceImpl)obj; easyServiceProxy.testEasyResult(); } }
Running effect:
##Achieved through JDk dynamic proxypublic class EasyServiceImplProxy implements InvocationHandler { private EasyServiceImpl target; public void setTarget(EasyServiceImpl target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 这里可以做增强 System.out.println("已经是代理类啦"); try{ return method.invoke(proxy, args); }catch (Exception e){ System.out.println("发生异常了"); return null; } } /** * 生成代理类 * @return 代理类 */ public Object CreatProxyedObj() { return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this); } }
How to force the use of CGLIB to implement AOP?
(1) Add the CGLIB library, SPRING_HOME/cglib/*.jar (2) AddWhat is the difference between JDK dynamic proxy and CGLIB bytecode generation?
(1) JDK dynamic proxy can only generate proxies for classes that implement interfaces, but not for classes (2) CGLIB implements proxies for classes, mainly for specified The class generates a subclass and overrides the methods Because it is inheritance, it is best not to declare the class or method as finalThe above is the detailed content of How to use AOP and interceptors to implement custom annotations in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!