Achieved using dynamic proxy to operate the database with the AOP

2008-06-02  来源:本站原创  分类:Java  人气:241 

A few days ago wrote "using dynamic proxy to achieve AOP functionality," the article, which is a two examples of a log and the other is about initialization parameters, for the practical application of little practical application today to write about the more commonly used to operate the database with the AOP.
The previous article has been to lay the entire framework, and now only need to implement a complete database, speaking interceptor can be done, and the following years we will achieve this interceptor.
To achieve the operation of the database is inseparable from the data source (DataSource) or connect (Connection), but generally speaking the operation of the database should be placed in DAO, but DAO not be associated with the application server, it is generally Using Connection (Connection). Now we have a problem here, and how to get connected in the interceptor. I think I can get in two ways:
In the two methods are discussed, we need to discuss when dealing with a database of exception handling. Here I made a TransactionException successor to RuntimeException and then thrown inside the interceptor, and then another application framework to deal with this exception. Next interview this class code:

public class TransactionException extends RuntimeException {
    private Throwable superException;
    private String myMessage;

    public TransactionException(Throwable throwable){
        super(throwable);
        this.superException = throwable;
    }

    public TransactionException(Throwable throwable,String message){
        super(message,throwable);
        this.superException = throwable;
        this.myMessage = message;
    }

    /**
     * @return Returns the myMessage.
     */
    public String getMessage() {
        return myMessage;
    }

    /**
     * @return Returns the superException.
     */
    public Throwable getSuperException() {
        return superException;
    }

    /**
     * @param myMessage The myMessage to set.
     */
    public void setMyMessage(String message) {
        this.myMessage = message;
    }

    /**
     * @param superException The superException to set.
     */
    public void setSuperException(Throwable superException) {
        this.superException = superException;
    }

}
1)     Through the first argument passed in
l    DAO
import java.sql.Connection;

public class TestDao {
    public void insertA(Connection con,String a,String b,--){
        ----------------
 A series of actions
----------------
    }

    public String queryA(Connection con,--.){
    ----------------
 A series of actions
----------------
}

    public void updateA(Connection con,--.){
        ----------------
 A series of actions
----------------
}
}

l     Interceptor
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TransactionInterceptor implements Interceptor {

    public void before(InvokeJniInfo invInfo) {
        if(isNeedTransactions(invInfo)){
            Connection conn = (Connection) invInfo.getArgs()[0];
            try {
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                throw new TransactionException(e);
            }
        }
    }

    public void after(InvokeJniInfo invInfo) {
        if(isNeedTransactions(invInfo)){
            Connection conn = (Connection) invInfo.getArgs()[0];
            try {
                conn.commit();
            } catch (SQLException e) {
                throw new TransactionException(e);
            }finally{
                if(conn != null){
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        throw new TransactionException(e,"Close Connection is failure!");
                    }
                }
            }
        }
    }

    public void exceptionThrow(InvokeJniInfo invInfo) {
        if(isNeedTransactions(invInfo)){
            Connection conn = (Connection) invInfo.getArgs()[0];
            try {
                conn.rollback();
            } catch (SQLException e) {
                throw new TransactionException(e);
            }finally{
                if(conn != null){
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        throw new TransactionException(e,"Close Connection is failure!");
                    }
                }
            }
        }
    }

    private List getNeedTransaction(){
        List needTransactions = new ArrayList();
        needTransactions.add("insert");
        needTransactions.add("update");
        return needTransactions;
    }

    private boolean isNeedTransactions(InvokeJniInfo invInfo){
        String needTransaction = "";
        List needTransactions = getNeedTransaction();
        for(int i = 0;i<needTransactions.size();i++){
            needTransaction = (String)needTransactions.get(i);
            if(invInfo.getMethod().getName().startsWith(needTransaction)){
                return true;
            }
        }
        return false;
    }
}

 It is important to note that  :getNeedTransaction It is necessary for the transaction to the beginning of the method, this method can be written as a class that derives from the configuration file inside to read  , Here I wrote die inside-only  insert And that begins with the update method of transaction control  .
2)     The Connection object in a  ThreadLocal In
l    ConnectionUtil Class  :
import java.sql.Connection;

public final class ConnectionUtil {
    private static ThreadLocal connections = new ThreadLocal();
    public static Connection getConnection(){
        Connection conn = null;
        conn = (Connection) connections.get();
        if(conn == null){
            conn = getRealConnection();
            connections.set(conn);
        }
        return conn;
    }
    public static void realseConnection(Connection conn){
        connections.set(null);
    }
    private static Connection getRealConnection() {
         Implement your own gets connection code
        return null;
    }
}
l    DAO Class
public class TestDao {
    public void insertA(String a,String b){
        Connection conn = getConnection();
        ----------------
 A series of actions
----------------
    }
        public String queryA(Connection con,--.){
        Connection conn = getConnection();
    ----------------
 A series of actions
----------------
}

    public void updateA(Connection con,--.){
Connection conn = getConnection();
        ----------------
 A series of actions
----------------
}

    private Connection getConnection(){
        return ConnectionUtil.getConnection();
    }

}
l     Interceptor
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TransactionInterceptor implements Interceptor {

    public void before(InvokeJniInfo invInfo) {
        if(isNeedTransactions(invInfo)){
            Connection conn = getConnection();
            try {
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                throw new TransactionException(e);
            }
        }
    }

    public void after(InvokeJniInfo invInfo) {
        if(isNeedTransactions(invInfo)){
            Connection conn = getConnection();
            try {
                conn.commit();
            } catch (SQLException e) {
                throw new TransactionException(e);
            }finally{
                if(conn != null){
                    try {
                        conn.close();
                        releaseConnection(conn);
                    } catch (SQLException e) {
                        throw new TransactionException(e,"Close Connection is failure!");
                    }
                }
            }
        }
    }

    public void exceptionThrow(InvokeJniInfo invInfo) {
        if(isNeedTransactions(invInfo)){
            Connection conn = getConnection();
            try {
                conn.rollback();
            } catch (SQLException e) {
                throw new TransactionException(e);
            }finally{
                if(conn != null){
                    try {
                        conn.close();
                        releaseConnection(conn);
                    } catch (SQLException e) {
                        throw new TransactionException(e,"Close Connection is failure!");
                    }
                }
            }
        }
    }

    private Connection getConnection(){
        return ConnectionUtil.getConnection();
    }

    private void releaseConnection(Connection conn){
        ConnectionUtil.releaseConnection(conn);
    }
    private List getNeedTransaction(){
        List needTransactions = new ArrayList();
        needTransactions.add("insert");
        needTransactions.add("update");
        return needTransactions;
    }

    private boolean isNeedTransactions(InvokeJniInfo invInfo){
        String needTransaction = "";
        List needTransactions = getNeedTransaction();
        for(int i = 0;i<needTransactions.size();i++){
            needTransaction = (String)needTransactions.get(i);
            if(invInfo.getMethod().getName().startsWith(needTransaction)){
                return true;
            }
        }
        return false;
    }
}
     Finally the AOP interceptors to intercept framework to  ,InterceptorHandler Class getIntercetors method, add a  :

    private synchronized List getIntercetors(){
        if(null == interceptors){
            interceptors = new ArrayList();
            --------------
interceptors.add(new TransactionInterceptor ());
            --------------
        }
        return interceptors;
}

 To the full  ok!
相关文章
  • Achieved using dynamic proxy to operate the database with the AOP 2008-06-02

    A few days ago wrote "using dynamic proxy to achieve AOP functionality," the article, which is a two examples of a log and the other is about initialization parameters, for the practical application of little practical application today to write

  • Proxy mode. Dynamic Proxy and aspect-oriented 2010-04-05

    A good understanding of the meaning of agent, which drew on the agent used in our daily meaning: that would have something to do this personally, for some reason can not directly do so, but only asked people to replace you do, what was your invited p

  • java dynamic proxy for cglib 2010-06-22

    cglib is a powerful high-performance code generation package, his extensive use by many of the AOP framework, such as Spring AOP and dynaop, to provide them with methods of interception (interception), the most popular of the OR Mapping tool is also

  • java dynamic proxy (JDK and cglib) 2010-06-28

    JAVA dynamic agency model agency model agency is a common java design patterns, characterized by his proxy class with the delegate class has the same interface, the proxy class is responsible for the delegate class pretreatment information, filtering

  • Proxy mode, JDK dynamic proxy, SpringAOP context 2010-03-29

    Here, we study how agents model, JDK dynamic proxy, as well as JDK-based proxy springAOP implementation model: the class structure of the model, advantage is that no changes to the original class (by proxy class) will be able to enhance the original

  • [Change] the use of JAVA in the dynamic proxy to achieve database connection pooling 2010-03-22

    Database connection pool in the preparation of applications often need to use the module, too frequent in terms of connecting to the database on the service performance is a bottleneck, the use of buffer pool technology to eliminate this bottleneck.

  • Dynamic Proxy 2010-02-14

    Dynamic Proxy design pattern is 23 a very common one, often look for the development of rights management systems, Spring in the AOP is the dynamic proxy approach, the following will describe Sun's JDK provides an implementation approach and provided

  • CGlib dynamic agent (to undertake the above JDK dynamic proxy) 2010-02-14

    1.CGLib dynamic proxy First, import the development kit: cglib.nodep.jar and Junit.jar Implementations with the JDK or less the same for the convenience of everyone reading the full implementation of the code will be written in the following The firs

  • JDK dynamic proxy 2010-03-29

    1. Using proxy mode to achieve agent (non-dynamic proxy) In order to understand what is a dynamic agency, we must first look at the static agent approach. Whether that agent approach, there is proxy object and the target audience two models, the so-c

  • spring dynamic proxy package MethodInvocation. lead to obtain the reasons for less than a method of annotation. 2010-03-29

    Because spring dynamic proxy package MethodInvocation. Led to obtain the reasons for less than a method of annotation. If you need to notify the spring before and after the words. . Generally be achieved MethodInterceptor public Object invoke (Method

  • Agent model and Java dynamic proxy class 2010-04-05

    1. <br /> Agency model agency model of the role is: to provide a proxy for other objects to control access to this object. In some cases, a client does not want or can not directly reference another object, and proxy object can be between the client

  • Java dynamic proxy. ASM and AOP 2010-06-08

    We know that inside there is a Java class java.lang.reflect.Proxy to achieve the so-called dynamic proxy, the core idea is dynamically generated at run time, a class that inherits java.lang.reflect.Proxy, to achieve the specified interfaces. Class wi

  • Dynamic agent (Dynamic Proxy) Java Proxy 2010-07-03

    Starting from JDK1.3, Java dynamic proxy on the introduction of the concept. Dynamic agent (Dynamic Proxy) can help you reduce the number of lines of code, to truly improve the code reusable in degrees. For example, you do not have all the class meth

  • java dynamic proxy mechanism 2010-07-11

    In the current Java Development Kit includes support for dynamic agency , But its implementation only supports the implementation of the interface . Its implementation is java.lang.reflect.Proxy class and mainly through java.lang.reflect.InvocationHa

  • Java, the static and dynamic proxy agent 2010-07-13

    1. Agents are mainly two models: the static and dynamic proxy agent 2. Static Agent: For example to output "HelloWorld" before printing a string "Welcome" A: first define an interface class package ttitfly.proxy; public interface Hello

  • struts2 interceptor (JDK reflection, JDK dynamic proxy) 2010-08-17

    The significance of the interceptor: As we all know, DRY (Don't Repeat Yourself, Do not write repetitive code) rules the software development process is an important law, to comply with the rules of the system will be developed with better maintainab

  • On the agent model and the understanding of Java dynamic proxy class (2 rpm) 2010-09-13

    1. Agency model agency model of the role is: to provide a proxy for other objects to control access to this object. In some cases, a client does not want or can not directly reference another object, and proxy objects can be the client and target aud

  • Spring AOP in the underlying implementation technology --- JDK dynamic proxy 2010-12-20

    <br /> JDK dynamic proxy provided in the JDK 1.3 dynamic proxy for the future technology that allows developers to create interfaces in the running of the proxy instance. Sun has just launched in the dynamic agent, it is difficult to imagine how muc

  • Java dynamic proxy agent model 2010-12-29

    Speaking yesterday, the static agents, static agents are known in advance the case of real objects generated proxy class, a proxy object that corresponds to a real object (proxy object holds a reference to the real object), if a lot of real objects n

  • Agent model. Dynamic proxy and aspect-oriented (to) 2011-01-05

    A good understanding of the meaning of agency, it draws on the agent used in our everyday meaning: that was supposed to personally do something, for some reason can not directly do, and can only ask someone to replace you do, this is your invited a l