码迷,mamicode.com
首页 > 编程语言 > 详细

Java dynamical proxy demo

时间:2015-02-28 07:47:08      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

今天练习了一下动态代理的一个方面,假设使用它来完成自动设置默认不提交,启动事务,获取到异常则回滚,正常执行则提交。

如果不使用动态代理,则需要在每个方法本身里面设置Connection,写try,catch语句,重复的工作。

为什么要使用动态代理?

我们的业务层可以更加专注于业务本身,把其他相关的活抽象出来共同处理,如日志处理和异常处理等。这样的代码更干净。

代码示例如下:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

interface DAO {
    public Connection GetConn(String url) throws SQLException;

    public void InsertData();

    public void GetData();

    public void DeleteData();
}

class myops implements DAO {
    @Override
    public void InsertData() {
        System.out.println("inserting data...");
    }

    @Override
    public void GetData() {
        System.out.println("getting data...");
    }

    @Override
    public void DeleteData() {
        System.out.println("deleting data...");
    }

    @Override
    public Connection GetConn(String url) throws SQLException {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Connection conn = null;
        conn = DriverManager
                .getConnection("jdbc:oracle:thin:@hostip:port:dbname",
                        "system", "pwd");
        return conn;
    }
}

class dynamicalproxy implements InvocationHandler {
    Object proxied;
    Connection conn;

    public dynamicalproxy(Object _proxied, Connection _conn) {
        proxied = _proxied;
        conn = _conn;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        Object rtv = null;
        conn.setAutoCommit(false);
        System.out.println("doing something before what ...");
        try {
            rtv = method.invoke(proxied, args);
        } catch (Exception ex) {
            conn.rollback();
            ex.printStackTrace();
        } finally {
            conn.commit();
            System.out.println("commit tran ...");
        }
        System.out.println("doing something after what ...");
        return rtv;
    }
}

public class proxydemo {
    public static void main(String[] args) throws IllegalArgumentException,
            SQLException {
        myops test = new myops();
        DAO dao = (DAO) Proxy.newProxyInstance(DAO.class.getClassLoader(),
                new Class[] { DAO.class },
                new dynamicalproxy(test, test.GetConn("")));
        dao.InsertData();
        dao.GetData();
        dao.DeleteData();
    }
}

Java dynamical proxy demo

标签:

原文地址:http://www.cnblogs.com/huaxiaoyao/p/4304635.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!