Home > Java > javaTutorial > How to use AOP and interceptors to implement custom annotations in SpringBoot

How to use AOP and interceptors to implement custom annotations in SpringBoot

PHPz
Release: 2023-05-29 19:58:00
forward
1051 people have browsed it

    Spring implements custom annotations

    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).

    1. Introduce related dependencies

    spring-boot-starter: Some core basic dependencies of spring

    spring-boot-starter-aop: Some related dependencies of spring to implement Aop

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

    2. Related classes

    1. Custom annotation class

    @Target({ElementType.TYPE})  //说明了Annotation所修饰的对象范围,这里,的作用范围是类、接口(包括注解类型) 或enum
    @Retention(RetentionPolicy.RUNTIME)  //自定义注解的有效期,Runtime:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在
    @Documented //标注生成javadoc的时候是否会被记录
    public @interface EasyExceptionResult {
    }
    Copy after login
    Copy after login

    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;
            }
        }
    }
    Copy after login

    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;
        }
     
    }
    Copy after login

    4. Use of custom annotations

    @Service
    @EasyExceptionResult  //自定义异常捕获注解
    public class EasyServiceImpl {
     
        public void testEasyResult(){
            throw new NullPointerException("测试自定义注解");
        }
     
    }
    Copy after login

    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();
        }
     
    }
    Copy after login

    How to use AOP and interceptors to implement custom annotations in SpringBoot

    So far, custom annotations have been implemented through spring.

    Java implements custom annotations

    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 {
    }
    Copy after login
    Copy after login

    @Target

    Indicates the java element type to which this annotation can be applied

    Target type Description
    ElementType.TYPEApplies to classes, interfaces (including annotation types), and enumerations
    ElementType.FIELDApplies to properties (including constants in enumerations)
    ElementType.METHODApplies to methods
    ElementType.PARAMETERFormal parameters applied to methods
    ElementType.CONSTRUCTORApplied to constructors
    ElementType.LOCAL_VARIABLEApply to local variables
    ElementType.ANNOTATION_TYPEApply to annotation types
    ElementType.PACKAGEApply to package
    ElementType.TYPE_PARAMETERNew in version 1.8, applied to type variables )
    ElementType.TYPE_USENew 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 typeDescription
    RetentionPolicy.SOURCEDiscarded at compile time and not included in the class file
    RetentionPolicy.CLASSDiscarded 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

    Achieved through Cglib

    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();
            }
     
        }
    Copy after login

    Running effect:

    How to use AOP and interceptors to implement custom annotations in SpringBoot

    ##Achieved through JDk dynamic proxy

    public 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);
        }
    }
    Copy after login
    The difference between Cglib and JDK dynamic proxy

    Java dynamic proxy uses the reflection mechanism to generate an anonymous class that implements the proxy interface, and calls InvokeHandler to process it before calling specific methods.

    The cglib dynamic proxy uses the asm open source package to load the class file of the proxy object class and modify its bytecode to generate a subclass for processing.

    1. If the target object implements the interface, JDK's dynamic proxy will be used by default to implement AOP

    2. If the target object implements the interface, CGLIB can be forced to be used to implement AOP

    3. If the target object does not implement the interface, the CGLIB library must be used. Spring will automatically convert between JDK dynamic proxy and CGLIB.

    How to force the use of CGLIB to implement AOP?

    (1) Add the CGLIB library, SPRING_HOME/cglib/*.jar

    (2) Add

    What 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 final

    The 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!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template