Simple Spring (iii) AOP detailed

Source: Internet
Author: User
Tags abstract aop exception handling
The Last post is simple and easy. Spring (ii) in the IOC detail, I gave you a brief introduction to the IOC in the core of the spring framework, and then we go on to another core AOP (Aspect oriented programming), the aspect-oriented programming.

1. Oop ReviewBefore introducing AOP, let's review the familiar OOP (Object oriented programming). OOP is mainly designed to achieve reusability, flexibility and scalability of programming. Some of its features are inheritance, encapsulation, polymorphism and abstraction. OOP focuses on the programming architecture, emphasizing the hierarchical relationships between classes.

2. Oop defectsTo better illustrate the concept of OOP, let's follow an example of OOP, focusing on what bugs exist in oop to better understand the relevant aspects of AOP.

First look at the following picture:



The above picture has three classes: Dog,cat and duck, and they all have a way to run. According to Oop's design philosophy, it's easy to think of abstracting a animal parent class, while allowing these three subclasses to inherit the animal parent class. Such a design can be represented in the following illustration:



In OOP, we use a large number of programming methods like the above graph to abstract, inherit, encapsulate and polymorphism the class to achieve reusability, flexibility and extensibility of programming. However, such programming still has some limitations, sometimes, OOP is not very good for us to solve the problems encountered in the actual development. To illustrate this issue, look at the following illustration:



Seeing the above picture, we can not find any problem at the moment. For everyone to understand, next I will explain to you the above class diagram implementation process. Described below: the circus has a performance puppy, the puppy can run and jump, but before it finishes running and jumping two moves, it must be after receiving an order from the trainer, and after running and jumping, the trainer will reward the response, such as a piece of meat.

After understanding the implementation process, we are looking at the specific code.

	public class Dog {public   
		void run () {
			System.out.println) ("The trainer makes a command.")
			System.out.println ("The puppy begins to run.") ");
			System.out.pringln ("Trainer gives reward");  
		public void Jump () {
			System.out.println () the trainer issued the order.
			System.out.println ("The puppy began to jump.") ");
			System.out.pringln ("Trainer gives reward");
		}
	

Looking at the code above, we can see that in the Run method and the Jump method, there are some of the same content (the trainer gives commands and rewards), and the content is not completely abstract, that is, it cannot be handled according to OOP programming ideas. Situations like this can also be found in many areas of our programming, such as logging, performance statistics, security control, transaction processing, exception handling, and so on. But how to solve this situation. This introduces the idea of AOP programming.


3. Introduction to AOP

AOP is the abbreviation of Aspect oriented programming, that is, aspect-oriented programming, which is a kind of technology that can be implemented dynamically and uniformly adding function without modifying the source code in the way of precompilation and runtime dynamic Proxy.


4. AOP Implementation example to better understand how AOP is implemented, let's optimize the above code.

First, the dog class.

	Public interface Animal {public
		void run ();
		public void jump ();
	}
	
	public class Dog implements animal{public
		void Run () {
			System.out.println ("puppy starts running.") ");
		}	
		public void Jump () {
			System.out.println ("Puppy starts jumping.") ");
		}		
	}

In contrast to the previous code, we can see clearly that the relevant content of the trainer is extracted from run and jump, and then how do we add the action of the trainer to the program during the program operation? This is the core technology dynamic proxy for the AOP implementation we used this time. The specific code is as follows:

import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import

Java.lang.reflect.Proxy;
	
	public class Myproxy implements invocationhandler{private Object targetobject; /** * Binds the delegate object and returns a proxy class * @param target * @return/public Object Createproxyinstance (object Targ		
		Etobject) {this.targetobject = TargetObject; Return Proxy.newproxyinstance (Targetobject.getclass (). getClassLoader (), Targetobject.getclass (). GetInterfaces ()
	, this);
	 /** * @param proxy: The object being represented. * @param methods: The method to invoke * @param args: Parameters required for method invocation/public object Invoke (Object Proxy, Method method, object[] args		
		Throws Throwable {//Inject the method command () that needs to be invoked;
		Executes the method of the proxy object, and assigns a value to the RET object ret = Method.invoke (targetobject, args) If the method has a return value;
		Inject the method that needs to be called award ();
	return ret; private void Command () {System.out.println () the trainer issued the command.
	"); private void Award () {System.out.println ("Trainer gives rewards.")
	"); }
}

After the completion of the above code implementation, we change how to call it. The reference code is as follows:

	public class Client {public
		static void Main (string[] args) {
			myproxy hander = new myproxy ();
			Animal dog = (Animal) hander.createproxyinstance (New Dog ());
			Dog.run ();
			Dog.jump ();
		}
	

The results of the implementation are as follows:



A demo of AOP programming is done, and then revisit the concepts of AOP and OOP.


5. The relationship between AOP and OOP OOP encapsulates the entities of the business process (Dog, Cat, Duck) and their properties and behaviors (run) for a clearer and more efficient logical unit partition. AOP, however, extracts the section (Command and award) of the business process (run or jump), and it faces a step or stage in the process of processing to obtain the isolation effect of the low coupling between the parts of the logic process. The two design ideas are fundamentally different from each other in the target.

The end of this article basically explains the concept of AOP, as for how to use AOP in spring, I'll cover an example in a future blog post, and we're not finished with AOP, and there are a lot of other concepts that I'll be able to explain in future posts. Please look forward to it.

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.