cglib動(dòng)態(tài)代理代碼示例
- 引用包c(diǎn)glib-xxx.jar
- 非Maven項(xiàng)目還需要手動(dòng)引用包asm-xxx.jar
- 業(yè)務(wù)類(不需要定義接口)
- cglib代理類(實(shí)現(xiàn)接口MethodInterceptor)
1江兢、業(yè)務(wù)類
package com.wzq.demo02;
/**
* 業(yè)務(wù)類
*
* 沒有實(shí)現(xiàn)接口
*
* 如果類是final的,則無法生成代理對(duì)象,報(bào)錯(cuò)
*
* 如果方法是final的捻浦,代理無效
*
* @author Muscleape
*
*/
public class UserServiceImpl {
public void addUser() {
System.out.println("增加一個(gè)用戶式撼。钠惩。貌亭。");
}
public void editUser() {
System.out.println("編輯一個(gè)用戶钳宪。屏歹。隐砸。");
}
}
2、cglib代理類蝙眶,需要實(shí)現(xiàn)接口MethodInterceptor
package com.wzq.demo02;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class UserServiceCglib implements MethodInterceptor {
private Object target;
public Object getInstance(Object target) {
this.target = target;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.target.getClass());
// 設(shè)置回調(diào)方法
enhancer.setCallback(this);
// 創(chuàng)建代理對(duì)象
return enhancer.create();
}
/**
* 實(shí)現(xiàn)MethodInterceptor接口中重寫的方法
*
* 回調(diào)方法
*/
@Override
public Object intercept(Object object, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("事務(wù)開始季希。。幽纷。");
Object result = proxy.invokeSuper(object, args);
System.out.println("事務(wù)結(jié)束式塌。。友浸。");
return result;
}
}
3峰尝、測(cè)試類
package com.wzq.demo02;
public class TestCglib {
public static void main(String[] args) {
UserServiceCglib cglib = new UserServiceCglib();
UserServiceImpl bookFacedImpl = (UserServiceImpl) cglib.getInstance(new UserServiceImpl());
bookFacedImpl.addUser();
}
}
4、測(cè)試結(jié)果
事務(wù)開始收恢。武学。祭往。
增加一個(gè)用戶。火窒。链沼。
事務(wù)結(jié)束。沛鸵。括勺。
5、異常信息(項(xiàng)目只引用了cglib包曲掰,沒有引用asm包)
Exception in thread "main" java.lang.NoClassDefFoundError: org/objectweb/asm/Type
at net.sf.cglib.core.TypeUtils.parseType(TypeUtils.java:184)
at net.sf.cglib.core.KeyFactory.<clinit>(KeyFactory.java:72)
at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:72)
at com.wzq.demo02.UserServiceCglib.getInstance(UserServiceCglib.java:15)
at com.wzq.demo02.TestCglib.main(TestCglib.java:6)
Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 5 more
FATAL ERROR in native method: JDWP on checking for an array class, jvmtiError=JVMTI_ERROR_WRONG_PHASE(112)
JDWP exit error JVMTI_ERROR_WRONG_PHASE(112): on checking for an array class [util.c:1299]