- 没有接口,只有实现类。
- 采用字节码增强框架 cglib,在运行时 创建目标类的子类,从而对目标类进行增强。
- 导入spring的核心包
![](https://i-blog.csdnimg.cn/blog_migrate/4c214b3204d242924e9fe19146160619.png)
- 上代码:
package com.fjs.Services;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/*
cglib 字节码增强
*/
public class MyBeanFactory {
public static Services createService2(){
//目标类
final Services service=new ServicesImpl();
//切面类
final MyAspect aspect=new MyAspect();
//cglib核心类
//创建增强对象
Enhancer enhancer=new Enhancer();
//设置父类
enhancer.setSuperclass(service.getClass());
//设置回调(拦截)
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object Proxy, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
/**
* proxy:
* om.gyf.service.StudentService$$EnhancerByCGLIB$$fbb8ef26
* proxy代理对象是StudentService的子类
*/
aspect.before();
Object obj=methodProxy.invokeSuper(Proxy,objects);
aspect.after();
return obj;
}
});
ServicesImpl proxy= (ServicesImpl) enhancer.create();
return proxy;
}
/*
JDK实现代理
*/
public static Services createService() {
//目标类
final Services service = new ServicesImpl();
//切面类
final MyAspect aspect = new MyAspect();
// public static Object newProxyInstance(ClassLoader loader,类加载器
// Class<?>[] interfaces,接口
// InvocationHandler h)处理
//代理类
Services serviceProxy = (Services) Proxy.newProxyInstance(
MyBeanFactory.class.getClassLoader(),
service.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//开启事物
aspect.before();
//service的返回值
Object obj = method.invoke(service, args);
//提交事物
aspect.after();
return obj;
}
}
);
return serviceProxy;
}
}