Enhancer 继承式代理
AOP
依赖
<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