Detailed description of encapsulation transactions in dynamic proxy Mode

Source: Internet
Author: User

Proxy, everyone knows what it means. The above explanation: In the name of another person, conduct legal actions directly against the agent within the scope of authorization.

To put it bluntly, a wants to make a girlfriend, but he does not dare to confess, and then asks B to help him send flowers, while B helps a to send flowers, and B is the proxy.

Proxy is divided into static proxy and dynamic proxy, so what is static proxy?

In the above example, A wants to have a girlfriend and then says to B: B, we are friends. I like girls. You want to help me with a bunch of flowers and help me with dolls, help me send chocolate ...... Then, when a wants to send the message, B will send the corresponding message.

The dynamic proxy is: A tells B that you can send flowers for me, And then B will send flowers. A also says that you can help me send dolls, and B will send dolls again ......

What is the difference between static proxy and dynamic proxy? Static proxy knows in advance that it is necessary to help a do those things, have psychological preparation, and take action faster. However, because a is very wordy, A needs to express strong love. After talking to B, B needs to write down what a wants to do and then help.

Dynamic proxy is that B is always busy with his own business. When a has a need, he will help a to send things, because a didn't tell B in advance what to send, so it takes some time to prepare B.

Okay, so much nonsense is to explain the proxy mode with my own understanding. The following is the question -- Dynamic proxy.

A dynamic proxy dynamically creates a proxy class at runtime, implements one or more interfaces, and forwards method calls to the specified class.

The proxy is completely created in Java and implements the complete subject interface.

Invocationhandler: this class is passed in for any method call on the proxy. invocationhandler controls access to the specific behavior class of realsubject.

Sun has already helped us create a proxy class proxy. What we need to do is to tell Proxy: what we want to do. We cannot write code into the proxy as before, because it is not created by us. If we create a proxy ourselves, it is a static proxy. There will be a lot of repeated code here, which we don't want to see. Because invocationhandler can respond to any call of the proxy, we can think of invocationhandler as the object for the request to perform inter-work after the proxy receives the method call.

The following example uses a dynamic proxy to encapsulate transactions:

Transactions are directly added to the manager layer in the previous project. The manager layer calls different Dao methods, starts transactions, and executes transactions. In addition to the business logic, each method in each manger layer must be responsible for the transaction switch. In fact, transactions are separate logics. We can dynamically separate the proxies.

Package COM. xxjstgb. 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 liuzhengquan **/public class transactionhandler implements invocationhandler {// the object to be processed, the object type is declared to be generic private object targetobject; // The object public ob after the method is dynamically generated Ject newproxyinstance (Object targetobject) implements this.tar GetObject = targetobject;/*** parameter 1: Class Loader * parameter 2: Determine the interface of the inherited class */return proxy. newproxyinstance (targetobject. getclass (). getclassloader (), targetobject. getclass (). getinterfaces (), this);} public object invoke (Object proxy, method, object [] ARGs) throws throwable {connection conn = NULL; object ret = NULL; try {// get connectionconn = connectionmanager. GETC Onnection (); // system. out. println (method. getname ();/** determines the method called by the manager layer. When this method is called, the transaction starts automatically * Note: errors exist in the DRP video */If (method. getname (). startswith ("addflowcard") | method. getname (). startswith ("delflowcard") | method. getname (). startswith ("modifyflowcard") | method. getname (). startswith ("findflowcardlist") | method. getname (). startswith ("findclient") | method. getname (). startswith ("findaimclient") {system. O Ut. println (method. getname (); // manually enable connectionmanager. begintransaction (conn);} // call the business logic method of the target object ret = method. invoke (targetobject, argS); If (! Conn. getautocommit () {// submit the connectionmanager transaction. committransaction (conn) ;}} catch (exception e) {e. printstacktrace (); // After the proxy is used, the proxy uses invocationtargetexception to wrap the exception if (E instanceof invocationtargetexception) {invocationtargetexception ete = (invocationtargetexception) E; throw ete. gettargetexception ();} If (! Conn. getautocommit () {// roll back the connectionmanager transaction. rollbacktransaction (conn);} Throw new applicationexception ("operation failed! ") ;}Finally {// close the transaction and delete the connectionmanager. closeconnection ();} return ret ;}}

The invoke method here, when a contemporary method is called, the proxy will forward this call to the invocationhandler, And it will call its invoke () method. In the invoke method, you can obtain the specific behavior method of realsubject and define new behaviors, that is, the transaction operation here.

* Note: there is an error in the video. The method. getname () method is called instead of the servlet method.

Servlet call:

Public class flowcardservlet extends httpservlet {// Private declares the specific behavior class Object private flowcardmanager; @ overridepublic void Init () throws servletexception {flowcardmanager = (flowcardmanager) getbeanfactory (). getserviceobject (flowcardmanager. class); // servicetransactionhandler transactionhandler = new transactionhandler () using dynamic proxy packaging; // generate proxy object flowcardmanager = (flowcardmanager) transactionhandler for the target. newproxyinstance (flowcardmanager );}}

In this way, we have created a flowcardmanager proxy. When we want to call methods at the manager layer, we can use the flowcardmanager proxy object in the servlet method, transaction operations and Manager-layer method calls.

Dynamic proxy applications are widely used. For example, a WebService application is actually an application of dynamic proxy. The reference we add to WebService is actually a remote proxy, and then the client can remotely access it through the proxy.

There are many examples in both life and practical applications, all of which have prototype agents. I hope you can communicate with me and make progress together.

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: 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.