AOP Dynamic Agent

Source: Internet
Author: User
Tags throwable

Aspect oriented programming is programming for facets. Decoupling is the development of programmer coding has been pursued in the process. AOP is also the birth of understanding the decoupling.

The concrete idea is: Define a slice, define the processing method in the vertical of the slice, and return to the horizontal business flow after the processing is done.

AOP is one of the core components of the spring framework, and indeed spring is a powerful feature of AOP. The most common is transaction control. After work, for the use of tools, inevitably need to understand the why. Learned a bit, wrote some procedures to help understand.

AOP is mainly implemented using the technology of proxy mode.

1, Static proxy: is the proxy mode in the design mode

A, business interface

/** * Abstract Theme role: A common interface that declares real topics and proxy topics. *  @author yanbin * *  /interface void talk (String msg);      

B, Business implementation

/*** Real Theme role: Define real objects. *  *@authorYanbin **/PublicClass PeopletalkImplementsItalk {PublicString username;PublicString age;PublicPeopletalk (string username, String age) {This.username =UsernameThis.age =Age }PublicvoidTalk (String msg) {System.out.println (msg + "! Hello, I am" + username + ", my age is" +Age ); } Public String getName () { return username;} public void setName (String name) { this.username = name;} public String getage () { return age ;} Public  void setage (String age) { this.age = Age ;}}       

C, proxy object

/*** Proxy Theme role: Contains a reference to a real topic internally, and provides the same interface as the real topic role. *  *@authorYanbin **/PublicClass TalkproxyImplementsItalk {private Italk talker; public Talkproxy (Italk talker) {// super (); this.talker = talker;} public void talk ( String msg) {talker.talk (msg);} public void talk ( String msg, String singname) {Talker.talk (msg); Sing (singname);} private void Sing ( String singname) {System.out.println ("singing:" + Singname);}}     

D, Test class

/*** Agent test class, using proxy * *@authorYanbin **/public classpublic static void main (string[] args) { // No additional methods are required. Italk people = new peopletalk ("AOP", "All" ); System.out.println ("-----------------------------" // (facets) Talkproxy talker = new Talkproxy (people); Talker.talk (" Proxy Test "," proxy " 

From this code can be seen, the proxy mode is actually the embryonic form of AOP. In the upper code, talk (String msg, String singname) is a facet. The Sing (Singname) method in the proxy class is a post-processing method.

This enables the decoupling of other auxiliary methods and business methods. The business does not need to be called specifically, but goes to the talk method, which logically calls the Sing method

Again from this code to see: 1, to implement proxy mode, you must define the interface. 2, each business class, need a proxy class.

2, dynamic agent:jdk1.5, using reflection. Implements the Invocationhandler interface.

The business interface is still a must, the business interface, the business is similar.

A, Agent class:

/*** Dynamic proxy class * *@authorYanbin **/PublicClass DynamicproxyImplementsInvocationhandler {/**Target classes that require proxies*/PrivateObject Target;/*** Fixed, AOP-only: Binds the delegate object and returns a proxy class * *@paramDelegate *@return*/PublicObject bind (object target) {This.target =TargetReturn Proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (),This); }/***@paramObject * Target: Refers to the objects being proxied. *@paramMethod #: Methods to Invoke *@param*/ @Override public object Invoke (Object proxy, Method method, object[] args) throws Throwable {Object result = null; // slice before executing System.out.println ("before slicing" ); // Execute business result =// after slice execution System.out.println ("Execute after Slice" ); return      

B, Test class

/** * Test class *  @author yanbin * * * *  /class void//new Dynamicproxy (). Bind (New Peopletalk ()); Italk.talk ("Business description");}}          

The output will be:

Slice before execution
People talk Business statement
Execution after Slice

Note that you can dynamically join a method that needs to be processed as long as the method slice is called by the business.

From the code point of view, if you build a business module, you only need a proxy class.  Italk Italk = (italk) new Dynamicproxy (). bind (New Peopletalk ()); Binds the business interface and the business class to the dynamic proxy class.

But this way: you still need to define an interface.

3. Using Cglib

Cglib is a proxy for classes, and his principle is to generate a subclass of the specified target class and override the method implementation enhancements. The way of inheritance is adopted. Do not elaborate, look at the use

A, Business class

/** * Business class *  @author yanbin * */  classvoid Talk (String msg) {System.out.println (" People talk "+ msg); }}

B, Cglib proxy class

/*** Use cglib dynamic agent * *@authorYanbin **/PublicClass CglibproxyImplementsMethodinterceptor {PrivateObject Target;/*** Create proxy Object * *@paramTarget *@return*/PublicObject GetInstance (object target) {This.target =Target Enhancer enhancer =NewEnhancer (); Enhancer.setsuperclass (This. Target.getclass ());// callback method Enhancer.setcallback (this ); // Create proxy object return Enhancer.create (); } @Override public object Intercept (object proxy, method, object[] args, Methodproxy methodproxy) throws Throwable {Object result = nullreturn      

C. Test class

/** * Test class * @author yanbin * * * */    classvoidnew Cglibproxy (). getinstance (New Peopletalk ()); Peopletalk.talk ("Business Method"); Peopletalk.spreak ("Business Method");}}          

The result of the final output:

Things start
People talk Business approach
The end of Things
Things start
Spreak Chinese Business method
The end of Things

Due to the limited space, this article mainly on the principle of AOP simple implementation of the demonstration and elaboration, to help their understanding. The implementation of spring's AOP implementations is no more than its right, but the implementation is much more complex.

AOP Dynamic Agent

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.