Enhancer

作者: 夏睡醒了秋 | 来源:发表于2019-11-14 22:59 被阅读0次

    Enhancer 继承式代理

    AOP

    image.png
    依赖
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.2.1.RELEASE</version>
    </dependency>
    

    MyAspect

    public class MyAspect {
        public void before(){
            System.out.println("----------before----------");
        }
    
        public void after(){
            System.out.println("----------after----------");
        }
    }
    

    XxxServiceImpl

    public class XxxServiceImpl {
        public void showClassName(){
            System.out.println("XxxServiceImpl");
        }
    }
    

    MyBeanFactory

    public class MyBeanFactory {
        public static Object createService(final Class clazz){
            // 切面类
            final MyAspect myAspect = new MyAspect();
    
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(clazz);
            enhancer.setCallback(new MethodInterceptor() {
                public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                    // 前
                    myAspect.before();
    
                    // 执行目标类的方法
                    Object obj = method.invoke(clazz.newInstance(),objects);
    
                    // 后
                    myAspect.after();
                    return obj;
                }
            });
            return enhancer.create();
        }
    }
    

    Main

    public class App {
        public static void main(String[] args) {
            XxxServiceImpl service = (XxxServiceImpl)MyBeanFactory.createService(XxxServiceImpl.class);
            service.showClassName();
        }
    }
    

    TEST

    image.png

    相关文章

      网友评论

          本文标题:Enhancer

          本文链接:https://www.haomeiwen.com/subject/tdgdictx.html