Enhancer

Enhancer 继承式代理

AOP

image.png

依赖


    org.springframework
    spring-core
    5.2.1.RELEASE

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)