5.2 analyze the Java proxy mechanism from an output log instance

Source: Internet
Author: User

 

5.2 analyze the Java proxy mechanism from an output log instance

As mentioned above, we should first understand the Java proxy mechanism to understand the AOP of spring. This section mainly analyzes the Java proxy mechanism through an instance that outputs logs. First, we will introduce how logs were previously written, and then explain how to use the Java proxy mechanism to output logs, next, I will explain how to use the dynamic proxy mechanism of Java to change the log output to a common one. Finally, I will introduce several key points of AOP.

5.2.1 common log output methods

In the programs developed before spring, whether using Java Automatic Log tool, log4j, or self-compiled log tool, you must write the log recording code in each business logic method. With AOP, the business logic and logging can be separated. The implementation idea of this output log instance is as follows: first, the method for writing logs in the program is provided, then the test program is compiled, the output result is viewed, and finally this method is summarized, points out the shortcomings of this method. The procedure is as follows:

(1) Open eclipse and create a Java file timebook. Java in the com. gc. action package to simulate the business logic of Attendance Review in actual business.

(2) When writing logs in a program, you must write the log-recorded code in each business logic method. The example code of timebook. Java is as follows:

// ******* Timebook. Java **************

Import org. Apache. log4j. level;

Import org. Apache. log4j. Logger;

Public class timebook {

Private logger = logger. getlogger (this. getclass (). getname ());

// Procedures for reviewing data

Public void doauditing (string name ){

Logger. Log (level. info, name + "start to review data ....");

// Procedures for reviewing data

......

Logger. Log (level. info, name + "audit data ends ....");

}

}

Code Description:

● Use log4j as a log output tool in business logic.

● The doauditing () method is used to process the attendance audit in the actual business.

● The parameter name is used to pass in the doauditing () method in the timebook class.

● The logger. Log () method is added before and after the review code to implement the log output function.

(3) write the test program and modify it based on testhelloworld. The sample code of testhelloworld. Java is as follows:

// ******** Testhelloworld. Java **************

Package com. gc. test;

Import com. gc. Action. timebook;

Public class testhelloworld {

Public static void main (string [] ARGs ){

Timebook = new timebook ();

Timebook. doauditing ("James ");

}

}

Code Description: timebook. doauditing ("Zhang San") indicates that the program executor is "Zhang San ".

(4) run the test program and view the log information output through the timebook class, as shown in Figure 5.1.

Figure 5.1 output log information through the timebook class

In the above example, the author adds the log information to the specific business logic. If other code in the program requires the log output function, then every program needs to add code similar to the above class. In this way, there will be a lot of similar log output code in the program, resulting in a lot of coupling. What method can be used to separate the business logic from the code of the output log? This problem can be improved through interface-oriented programming.

5.2.2 implement log output through interface-Oriented Programming

With the preceding sample program, you can learn about the disadvantages of the method for adding log information. The following describes how to improve this disadvantage through interface-oriented programming. The implementation idea is: first extract the doauditing () method that executes the attendance audit into an interface, and then implement this method through an entity class, in this method, write the specific business logic of attendance audit, then use a proxy class to output logs, and finally write a test program to view the output results. The procedure is as follows:

(1) create an interface timebookinterface in the com. gc. impl package. The example code of timebookinterface. Java is as follows:

// ******* Timebookinterface. Java **************

Package com. gc. impl;

Import org. Apache. log4j. level;

// Implement log output through interface-Oriented Programming

Public interface timebookinterface {

Public void doauditing (string name );

}

(2) In the com. gc. action package, enable the previously established Class timebook to implement the interface timebookinterface, and write the Specific attendance audit code in the doauditing () method. The example code of timebook. Java is as follows:

// ******* Timebook. Java **************

Package com. gc. Action;

Import com. gc. impl. timebookinterface;

Public class timebook implements timebookinterface {

Public void doauditing (string name ){

// Procedures for reviewing data

......

}

}

(3) Compile a proxy class to implement log output. In this class, program the previous interface timebookinterface, instead of specific classes, to implement specific business logic and log output code. The example code of timebookproxy. Java is as follows:

// ******* Timebookproxy. Java **************

Package com. gc. Action;

Import org. Apache. log4j. level;

Import org. Apache. log4j. Logger;

Import com. gc. impl. timebookinterface;

Public class timebookproxy {

Private logger = logger. getlogger (this. getclass (). getname ());

Private timebookinterface;

// This class is used to program the timebookinterface of the preceding interface, instead of the specific class.

Public timebookproxy (timebookinterface ){

This. timebookinterface = timebookinterface;

}

// Actual Service Processing

Public void doauditing (string name ){

Logger. Log (level. info, name + "start to review data ....");

Timebookinterface. doauditing (name );

Logger. Log (level. info, name + "audit data ends ....");

}

}

(4) modify the test program testhelloworld and pass the timebook class into the proxy timebookproxy as a parameter to call the timebook class for Attendance Review. The sample code of testhelloworld. Java is as follows:

// ******** Testhelloworld. Java **************

Package com. gc. test;

Import com. gc. Action. timebook;

Import com. gc. Action. timebookproxy;

Public class testhelloworld {

Public static void main (string [] ARGs ){

// Programming the interface

Timebookproxy = new timebookproxy (New timebook ());

Timebookproxy. doauditing ("James ");

}

}

(5) run the test program to obtain the log output through the timebookproxy class, as shown in Figure 5.2.

Figure 5.2 output log information through the timebookproxy class

Compared with the previous log output, we can see that in this example, the specific business logic code for Attendance Review and the log information code are separated, in addition, as long as the timebookinterface class is implemented, you can use the proxy class timebookproxy to output log information, instead of writing the log information output code in each class, this enables code reuse of log information.

5.2.3 use the Java proxy mechanism for log output

Although the previous Code has made some improvements, it still has some limitations, because to use the proxy class, you must implement a fixed interface. Is there a general mechanism, whether this interface is implemented or not, can log information be output?

The invocationhandler interface provided by Java can implement this function. First, write a proxy class for log information. This proxy class implements the invocationhandler interface, and then writes an interface similar to the previous instance, and implement this interface, write the Specific attendance audit code in the implementation class, and finally write the test class for the interface to view the test results. The procedure is as follows:

(1) Compile a log information proxy logproxy, which implements the interface invocationhandler and can output log information to any interface. The sample code of logproxy. Java is as follows:

// ******** Logproxy. Java **************

Package com. gc. Action;

Import java. Lang. Reflect. invocationhandler;

Import java. Lang. Reflect. method;

Import java. Lang. Reflect. proxy;

Import org. Apache. log4j. level;

Import org. Apache. log4j. Logger;

// The proxy class implements the invocationhandler interface.

Public class logproxy implements invocationhandler {

Private logger = logger. getlogger (this. getclass (). getname ());

Private object delegate;

// Bind a proxy object

Public object BIND (Object delegate ){

This. Delegate = delegate;

Return proxy. newproxyinstance (delegate. getclass (). getclassloader (), delegate. getclass ().
Getinterfaces (), this );

}

// Programming for interfaces

Public object invoke (Object proxy, method, object [] ARGs) throws throwable {

Object result = NULL;

Try {

// Log output before and after method call

Logger. Log (level. info, argS [0] + "start to review data ....");

Result = method. Invoke (delegate, argS );

Logger. Log (level. info, argS [0] + "End of data review ....");

} Catch (exception e ){

Logger. Log (level. info, E. tostring ());

}

Return result;

}

}

(2) Use the interface timebookinterface in the com. gc. impl package. The example code of timebookinterface. Java is as follows:

// ******* Timebookinterface. Java **************

Package com. gc. impl;

Import org. Apache. log4j. level;

// Programming for interfaces

Public interface timebookinterface {

Public void doauditing (string name );

}

(3) Use the timebook class in the com. gc. action package and the doauditing () method to write the Specific attendance audit code. The example code of timebook. Java is as follows:

// ******* Timebook. Java **************

Package com. gc. Action;

Import com. gc. impl. timebookinterface;

Public class timebook implements timebookinterface {

Public void doauditing (string name ){

// Procedures for reviewing data

......

}

}

(4) modify the test code testhelloworld and use the log proxy logproxy to output logs. The sample code of testhelloworld. Java is as follows:

// ******** Testhelloworld. Java **************

Package com. gc. test;

Import com. gc. Action. timebook;

Import com. gc. Action. timebookproxy;

Import com. gc. impl. timebookinterface;

Import com. gc. Action. logproxy;

Public class testhelloworld {

Public static void main (string [] ARGs ){

// Achieves reuse of log classes

Logproxy = new logproxy ();

Timebookinterface timebookproxy = (timebookinterface) logproxy. BIND (New timebook ());

Timebookproxy. doauditing ("James ");

}

}

(5) run the test program to obtain the log output information through the logproxy class, as shown in Figure 5.3.

Figure 5.3 output log information through the logproxy class

This method is also applicable to other classes, which truly achieves the separation of business logic and output log information code.

5.2.4 summarize the three implementation methods

The first method is to add the code for the output log information in each class. The second method is to separate the business logic from the output log information code, however, it must still rely on fixed interfaces. The third method is to reuse the output log information code and not rely on Fixed Interface implementation.

From the third method, we can also see that the Java Dynamic proxy mechanism is powerful, and spring's AOP is based on Java Dynamic proxy, after reading the examples above, you can get to know Java's dynamic proxy mechanism step by step.

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.