java学习

java学习

 

设计模式之cglib的动态代理

cglib的动态生成的代理对象是目标类的子类。
public class Classes implements Serializable{
private Long cid;
public Long getCid() {
return cid;
}
public void setCid(Long cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
private String cname;
private String description;
}
public interface ClassesDao {
public void saveClasses(Classes classes);
}
public class ClassesDaoImpl implements ClassesDao{
@Override
public void saveClasses(Classes classes) {
System.out.println("保存");
}
}
public class ClassesDaoInterceptor implements MethodInterceptor {
private Object target;
private MyTransaction myTransaction;
public ClassesDaoInterceptor(Object target, MyTransaction myTransaction) {
this.target = target;
this.myTransaction = myTransaction;
}
public Object create() {
Enhancer en = new Enhancer();
en.setSuperclass(target.getClass());
en.setCallback(this);
return en.create();
}
@Override
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy arg3) throws Throwable {
System.out.println(proxy.getClass().getName());
System.out.println(arg3.getSuperName());
if (method.getName().equals("saveClasses")
|| method.getName().equals("updateClasses")) {
this.myTransaction.beginTransaction();// ֪ͨ
method.invoke(this.target, args);// Ŀ�귽��
this.myTransaction.commit();
} else {
method.invoke(this.target, args);
}
return null;
}
}
public class MyTransaction {
public void beginTransaction(){
System.out.println("开始事务");
}
public void commit(){
System.out.println("提交事务");
}
}
public class ClassesDaoTest {
public static void testSaveClasses(){
Object dao = new ClassesDaoImpl();
MyTransaction myTransaction = new MyTransaction();
ClassesDaoInterceptor interceptor = new ClassesDaoInterceptor(dao, myTransaction);
ClassesDaoImpl proxyDao= (ClassesDaoImpl) interceptor.create();
Classes classes = new Classes();
classes.setCname("aaaa");
proxyDao.saveClasses(classes);
}
public static void main(String[] args) {
testSaveClasses();
}
}

posted on 2017-09-14 15:41 杨军威 阅读(123) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜