aop学习总结二------使用cglib动态代理简单实现aop功能

时间:2021-12-21 04:33:56

aop学习总结二------使用cglib动态代理简单实现aop功能

模拟业务需求:

1.拦截所有业务方法

2.判断用户是否有权限,有权限就允许用户执行业务方法,无权限不允许用户执行业务方法

(判断是否有权限是根据user是否为null)

CGLIB的代理:目标对象没有实现接口

业务类:

package ql.service.impl;

public class PersonServiceBean {

    private String user=null;

    public PersonServiceBean(){}

    public PersonServiceBean(String user){
this.user=user;
} public String getUser() {
return user;
} public void setUser(String user) {
this.user = user;
} public void save(String name) { System.out.println("我是save()方法");
} public void update(String name, Integer personId) {
System.out.println("我是update()方法");
} public String getPersonName(Integer personId) {
System.out.println("我是getPersonName()方法");
return "success";
} }

CGLIB动态代理工厂类:

package ql.aop;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import ql.service.impl.PersonServiceBean; public class CGLIBProxyFactory implements MethodInterceptor { // 目标对象
private Object targetObject; // 得到一个代理实例
public Object createProxyIntance(Object targetObject) {
this.targetObject = targetObject;
// 该类用于生产代理对象
Enhancer enhancer = new Enhancer();
// 继承了目标对象,对目标类的所有非final方法进行覆盖,并加上自己的代码
enhancer.setSuperclass(this.targetObject.getClass());
enhancer.setCallback(this);
return enhancer.create();
} public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy methodProxy) throws Throwable {
PersonServiceBean bean = (PersonServiceBean) this.targetObject; Object result = null;
if (bean.getUser() != null) {
result = methodProxy.invoke(targetObject, args);
}
return result;
}
}

单元测试类:

package ql.test;

import org.junit.Before;
import org.junit.Test; import ql.aop.CGLIBProxyFactory;
import ql.service.impl.PersonServiceBean; public class ProxyTest { @Before
public void setUp() throws Exception {
} @Test
public void testCGLIBProxyFactory1() { CGLIBProxyFactory cglibProxyFactory=new CGLIBProxyFactory();
PersonServiceBean personServiceBean=(PersonServiceBean) cglibProxyFactory.createProxyIntance(new PersonServiceBean());
personServiceBean.save("小明");
}
@Test
public void testCGLIBProxyFactory2() {
CGLIBProxyFactory cglibProxyFactory=new CGLIBProxyFactory();
PersonServiceBean personServiceBean=(PersonServiceBean) cglibProxyFactory.createProxyIntance(new PersonServiceBean("xxxx"));
personServiceBean.save("小明");
} }