通过cglab 实现 Spring AOP
-
-
1新建一个目标类
public class StudentService {
public void delete(){
System.out.println("删除学生");
}
public void add(){ System.out.println("添加学生"); }
public void update(){
System.out.println("更新学生");
}
}
切面类: 增强代码与切入点结合public class MyAspect {
public void before(){
System.out.println("开启事务");
}
public void after(){
System.out.println("提交事务");
}
}2.新建一个工厂类
public class MyBeanFactory {
public static StudentService createStudentService(){
//1创建对象
final StudentService studentService= new StudentService();
System.out.println(studentService);
//2声明切面类对象
final MyAspect aspect=new MyAspect();
//3 创建增强对象
Enhancer enhancer= new Enhancer();
//4 设置父类
enhancer.setSuperclass(studentService.getClass());
//设置回调 拦截
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
/**
* class com.zz.service.StudentService$$EnhancerByCGLIB$$c7d7b405
* org.springframework.cglib.proxy.MethodProxy@53bbfa
*/
// System.out.println(o.getClass());
System.out.println(methodProxy);
aspect.before();
//放行
Object retObj = methodProxy.invokeSuper(proxy,args);
aspect.after();
System.out.println("拦截....");
return retObj;
}
});
//创建代理对象
StudentService serviceProxy = (StudentService) enhancer.create();
// System.out.println(proxyService);
return serviceProxy;
}
} - 测试结果:由cglab 创建对象并实现成功
-
-