Encapsulate transactions using dynamic proxies

Source: Internet
Author: User

If you use a three-tier architecture for development, you must manually operate the transaction at the business logic layer. Therefore, there will be many unrelated business logic at the business logic layer: Connection conn = ConnectionManage. getConnection (); ConnectionManage. beginTransaction (conn); ConnectionManage. commitTransaction (conn); and so on. Not only unreasonable, but also repetitive work. One principle of program development is to put an end to repetitive work and achieve good encapsulation. Here, we use dynamic proxies to encapsulate transactions, so that the business logic layer no longer displays the relevant transaction code. [Java] package com. jialin. drp. util; import java. lang. reflect. invocationHandler; import java. lang. reflect. invocationTargetException; import java. lang. reflect. method; import java. lang. reflect. proxy; import java. SQL. connection;/*** use dynamic proxy to encapsulate Transactions * @ author jialin **/public class TransactionHandler implements InvocationHandler {private Object targetObject; /*** get the proxy of the target class * @ param targetObject * @ retu Rn */public Object newProxyInstance (Object targetObject) {this.tar getObject = targetObject; return Proxy. newProxyInstance (targetObject. getClass (). getClassLoader (), targetObject. getClass (). getInterfaces (), this);}/*** proxy Method. Call this method before calling the target Class Method */@ Override public Object invoke (Object proxy, method Method method, object [] args) throws Throwable {Connection conn = null; Object ret = null; try {// from ThreadLo Obtain the Connection in cal. ConnectionManage is the encapsulation of connection. conn = ConnectionManage. getConnection (); // if it is a method starting with add, del, modify, the transaction if (method. getName (). startsWith ("add") | method. getName (). startsWith ("del") | method. getName (). startsWith ("modify") {// manually control the ConnectionManage of the transaction commit. beginTransaction (conn);} // call the business logic method of the target object ret = method. invoke (targetObject, args); // if the transaction is manually committed, the transaction if (! Conn. getAutoCommit () {// submit the ConnectionManage transaction. commitTransaction (conn) ;}} catch (Exception e) {// if the transaction is submitted manually, roll back the transaction manually if (! Conn. getAutoCommit () {// roll back the ConnectionManage of the transaction. rollbackTransaction (conn);} e. printStackTrace (); if (e instanceof InvocationTargetException) {InvocationTargetException ete = (InvocationTargetException) e; throw ete. getTargetException ();} throw new Exception ("operation failed! ");} Finally {// close the ConnectionManage connection. closeConnection () ;}return ret ;}} package com. jialin. drp. util; import java. lang. reflect. invocationHandler; import java. lang. reflect. invocationTargetException; import java. lang. reflect. method; import java. lang. reflect. proxy; import java. SQL. connection;/*** use dynamic proxy to encapsulate Transactions * @ author jialin **/public class TransactionHandler implements InvocationHandler {private O Bject targetObject;/*** get the Proxy of the target class * @ param targetObject * @ return */public Object newProxyInstance (Object targetObject) implements this.tar getObject = targetObject; return Proxy. newProxyInstance (targetObject. getClass (). getClassLoader (), targetObject. getClass (). getInterfaces (), this);}/*** proxy Method. Call this method before calling the target Class Method */@ Overridepublic Object invoke (Object proxy, method Method method, object [] args) throws Throwable {Connection Conn = null; Object ret = null; try {// obtain the Connection from ThreadLocal. ConnectionManage is the encapsulation of connection. conn = ConnectionManage. getConnection (); // if it is a method starting with add, del, modify, the transaction if (method. getName (). startsWith ("add") | method. getName (). startsWith ("del") | method. getName (). startsWith ("modify") {// manually control the ConnectionManage of the transaction commit. beginTransaction (conn);} // call the business logic method of the target object ret = method. invoke (targetObject, args); // if the transaction is manually committed, the transaction if (! Conn. getAutoCommit () {// submit the ConnectionManage transaction. commitTransaction (conn) ;}} catch (Exception e) {// if the transaction is submitted manually, roll back the transaction manually if (! Conn. getAutoCommit () {// roll back the ConnectionManage of the transaction. rollbackTransaction (conn);} e. printStackTrace (); if (e instanceof InvocationTargetException) {InvocationTargetException ete = (InvocationTargetException) e; throw ete. getTargetException ();} throw new Exception ("operation failed! ");} Finally {// close the ConnectionManage connection. closeConnection ();} return ret;} principle: when we get the business logic layer object in the factory, what we get is not the target object, but the proxy of the target object, the proxy enables, commits, rolls back, and disables the management of transactions for us. In the factory, use a dynamic proxy to wrap the business logic Object [java] public synchronized Object GetServiceBean (Class c) {if (ServiceMap. containsKey (c. getName () {return ServiceMap. get (c. getName ();} Element beanEle = (Element) doc. selectSingleNode ("// Service [@ id = \" "+ c. getName () + "\"] "); String className = beanEle. attributeValue ("class"); // System. out. print (className); Object serviceBean = null; try {serviceBean = Class. forName (className ). newInstance (); // use dynamic proxy to package Service TransactionHandler transactionHandler = new TransactionHandler (); // obtain proxy serviceBean = transactionHandler. newProxyInstance (serviceBean); ServiceMap. put (c. getName (), serviceBean);} catch (Exception e) {throw new RuntimeException ();} return serviceBean;} public synchronized Object GetServiceBean (Class c) {if (ServiceMap. containsKey (c. getName () {return ServiceMap. get (c. getName ();} Element beanEle = (Element) doc. selectSingleNode ("// Service [@ id = \" "+ c. getName () + "\"] "); String className = beanEle. attributeValue ("class"); // System. out. print (className); Object serviceBean = null; try {serviceBean = Class. forName (className ). newInstance (); // use dynamic proxy to package ServiceTransactionHandler transactionHandler = new TransactionHandler (); // obtain the proxy www.2cto. comserviceBean = transactionHandler. newProxyInstance (serviceBean); ServiceMap. put (c. getName (), serviceBean);} catch (Exception e) {throw new RuntimeException ();} return serviceBean;} // The retrieved object is not the target object, instead, the proxy [java] userManager = (UserManager) getBeanFactory () of the target object (). getServiceBean (UserManager. class); userManager = (UserManager) getBeanFactory (). getServiceBean (UserManager. class );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.