使用CGlib实现AOP功能

直接上代码了。

实现类
 1 package com.cglib.service.impl;
2
3 public class AopServiceImpl {
4
5 private String user = null;
6
7 public String getUser() {
8 return user;
9 }
10
11 public void setUser(String user) {
12 this.user = user;
13 }
14
15 public AopServiceImpl() {
16 }
17
18 public AopServiceImpl(String user) {
19 this.user = user;
20 }
21
22 public void save() {
23 System.out.println("调用了save()方法");
24 }
25 }
CGlib工厂类
 1 package com.cglib.factory;
2
3 import java.lang.reflect.Method;
4
5 import com.cglib.service.impl.AopServiceImpl;
6
7 import net.sf.cglib.proxy.Enhancer;
8 import net.sf.cglib.proxy.MethodInterceptor;
9 import net.sf.cglib.proxy.MethodProxy;
10
11 public class CGlibFactory implements MethodInterceptor {
12
13 private Object targetObject = null;
14
15 public Object creatObjectIntance(Object targetObject) {
16 this.targetObject = targetObject;
17 Enhancer enhancer = new Enhancer();
18 //设置父类
19 enhancer.setSuperclass(this.targetObject.getClass());
20 //设置回调函数
21 enhancer.setCallback(this);
22 return enhancer.create();
23 }
24
25 @Override
26 public Object intercept(Object object, Method method, Object[] args,
27 MethodProxy proxy) throws Throwable {
28 AopServiceImpl aopServiceImpl = (AopServiceImpl) this.targetObject;
29 if (aopServiceImpl.getUser() != null) {
30 return proxy.invoke(this.targetObject, args);
31 }
32 return null;
33 }
34 }
单元测试
 1 package junit.test;
2
3 import org.junit.Test;
4
5 import com.cglib.factory.CGlibFactory;
6 import com.cglib.service.impl.AopServiceImpl;
7
8 public class CGlibUnitTest {
9 @Test public void CGlibTest(){
10 CGlibFactory cGlibFactory=new CGlibFactory();
11 AopServiceImpl aopServiceImpl=(AopServiceImpl)cGlibFactory.creatObjectIntance(new AopServiceImpl("test"));
12 aopServiceImpl.save();
13 }
14 }




你可能感兴趣的:(cglib)