代理模式----能进行事务的注解
(做一个生成代理模式的工具类;把调用其中的getProxy(传入原型对像));这时返回值就是一个代理后的对象
Transaction .java
@Retention(RetentionPolicy.RUNTIME)//运行时环境
@Target(value=ElementType.METHOD)//指定该注解在哪里起作用
public @interface Transaction {
}
TXProxy.java
public class TXProxy implements InvocationHandler{
private Object srcObj;//原型对象
public TXProxy(Object srcObj) {
this.srcObj = srcObj;
}
@SuppressWarnings("unchecked")
public static<E> E getProxy(E srcObj){//这里用泛型;到时调用的时候不用强转
Object proxideObj=Proxy.newProxyInstance(
TXProxy.class.getClassLoader(),
srcObj.getClass().getInterfaces(),
new TXProxy(srcObj));
return (E) proxideObj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
boolean boo=method.isAnnotationPresent(Transaction.class);
Connection con=null;
if(boo){//判断该方法上是否有注解
try {
con=ConnEndUtils.getConn();
con.setAutoCommit(false);
System.out.println("事务开启了");
//前面栏
Object res= method.invoke(srcObj, args);//放行
con.commit();
System.out.println("事务提交了");
return res;
//后面栏
} catch (Exception e) {
try {
con.rollback();
System.out.println("事务回滚了");
} catch (SQLException e1) {
throw new RuntimeException("数据库回滚失",e1);
}
}finally{
try {
con.setAutoCommit(true);
con.close();
} catch (SQLException e) {
throw new RuntimeException("数据库关闭失败!", e);
}
}
return null;
}else{
//没有注解放行;原样执行
return method.invoke(srcObj, args);
}
}
}
(做一个生成代理模式的工具类;把调用其中的getProxy(传入原型对像));这时返回值就是一个代理后的对象
Transaction .java
@Retention(RetentionPolicy.RUNTIME)//运行时环境
@Target(value=ElementType.METHOD)//指定该注解在哪里起作用
public @interface Transaction {
}
TXProxy.java
public class TXProxy implements InvocationHandler{
private Object srcObj;//原型对象
public TXProxy(Object srcObj) {
this.srcObj = srcObj;
}
@SuppressWarnings("unchecked")
public static<E> E getProxy(E srcObj){//这里用泛型;到时调用的时候不用强转
Object proxideObj=Proxy.newProxyInstance(
TXProxy.class.getClassLoader(),
srcObj.getClass().getInterfaces(),
new TXProxy(srcObj));
return (E) proxideObj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
boolean boo=method.isAnnotationPresent(Transaction.class);
Connection con=null;
if(boo){//判断该方法上是否有注解
try {
con=ConnEndUtils.getConn();
con.setAutoCommit(false);
System.out.println("事务开启了");
//前面栏
Object res= method.invoke(srcObj, args);//放行
con.commit();
System.out.println("事务提交了");
return res;
//后面栏
} catch (Exception e) {
try {
con.rollback();
System.out.println("事务回滚了");
} catch (SQLException e1) {
throw new RuntimeException("数据库回滚失",e1);
}
}finally{
try {
con.setAutoCommit(true);
con.close();
} catch (SQLException e) {
throw new RuntimeException("数据库关闭失败!", e);
}
}
return null;
}else{
//没有注解放行;原样执行
return method.invoke(srcObj, args);
}
}
}