Four implementation methods of spring AOP

Source: Internet
Author: User
Four Methods for Implementing AOP in Spring

Hot23 Chi Hong ze 2010-07-27
Only 980 RMB for learning Java

First, understand the related terminology of AOP:
1. Notification (Advice ):
The notification defines what the aspect is and when to use it. Describes the work to be done and when to execute the work.
2. Join point (Joinpoint ):
The program can apply a "time" of the notification, which is the connection point, such as when the method is called or an exception is thrown.
3. Pointcut)
The notification defines the "story" and the time when the "story" takes place. The starting point defines the location where the "story" takes place, such as the name of a class or method, spring allows us to easily use regular expressions to specify
4. Aspect)
The notification and the entry point form the intersection: time, location, and "story" to happen"
5. Introduction (Introduction)
Introduction allows us to add new methods and attributes to existing classes (Spring provides a method injection function)
6. Target)
That is, the notification object. If no AOP is available, its logic will be divided into other transaction logic, with AOP, it can focus only on what you want to do (AOP allows him to do what he wants to do with sex)
7. proxy)
The object of the Application Notification. For details, see the proxy mode in the design mode.
8. Weaving)
The process of applying a cut surface to a target object to create a new proxy object is usually as follows:
(1) Compile time: When a class file is compiled, it is woven into a special compiler. For example, AspectJ can be woven into the compiler.
(2) class loading: use special ClassLoader to enhance the byte code of the class before the target class is loaded to the program.
(3) runtime: the plane is woven into the plane at a certain time during runtime. SpringAOP is woven into the plane in this way. The principle should be that the dynamic proxy technology of JDK is used.

Spring provides four methods to implement AOP:
1. Classic proxy-based AOP
2. @ AspectJ annotation-driven aspect
3. Pure POJO Section
4. Injection AspectJ aspect

First, let's look at the Classic proxy-based AOP:
Spring supports five types of notifications:
Before (Front) org. apringframework. aop. MethodBeforeAdvice
After-returning (After return) org. springframework. aop. AfterReturningAdvice
After-throwing (After throw) org. springframework. aop. ThrowsAdvice
Arround (surrounding) org. aopaliance. intercept. MethodInterceptor
Introduction (introduced) org. springframework. aop. IntroductionInterceptor

The value indicates the surrounding notifications, which are defined by the interfaces in the AOP Alliance, rather than Spring, the surrounding notifications are equivalent to the combination of previous notifications, post-return notifications, and post-throw notifications (the legendary full body? Okay, I'll watch the day and watch more

I haven't figured out how to play with the introduction notice, so I can play it when I have no distractions.

How can this problem be solved? These steps:
1. Create a notification: implement these interfaces and implement the methods.
2. Define the cut point and notification: configure the information in the Spring configuration file.
3. Use ProxyFactoryBean to generate a proxy

Specific practices... Let's take an example of sleeping at night:

First, write an interface called Sleepable, which is a cool X interface. All things with sleep ability can implement this interface (not only creature, but also sleep in the Shutdown option)

Package test. spring. aop. bean

Public interface Sleepable {

Void sleep ();
}

Then write a Human class, which implements this interface.

Package test. spring. aop. bean

Public Human implements Sleepable {

/* Is this person similar to a few people?
* Nothing except sleeping well? */
Public void sleep (){
System. out. println ("sleeping! You have your own face in your dream! ");
}

}

Well, this is the main character, but before and after going to bed to do some auxiliary work, the most basic thing is to take off your clothes, insomnia people also want to take sleeping pills or something, however, these actions are irrelevant to the "business logic" of pure sleep.

Is it against a single responsibility to add all these codes to the sleep method ?, Now we need AOP.

Write a SleepHelper class that includes the auxiliary work of sleeping. In AOP terminology, it should be a notification. We need to implement the above interface.

Package test. spring. aop. bean;

Import java. lang. reflect. Method;

Import org. springframework. aop. AfterReturningAdvice;
Import org. springframework. aop. MethodBeforeAdvice;

Public class SleepHelper implements MethodBeforeAdvice, AfterReturningAdvice {

Public void before (Method mtd, Object [] arg1, Object arg2)
Throws Throwable {
System. out. println ("usually take off your clothes before going to bed! ");
}

Public void afterReturning (Object arg0, Method arg1, Object [] arg2,
Object arg3) throws Throwable {
System. out. println ("wear clothes first after you get up! ");
}

}

Then configure in the spring configuration file:
<Bean id = "sleepHelper" class = "test. spring. aop. bean. SleepHelper">
</Bean>

OK! Now the notification creation is complete.

The second step is configuration. This is a very painful operation. Especially on such a hot day, Spring puts the name of things to hell! Why can't it look like usr?

The first thing to do is to configure a cut point. It is said that there are several cut points in Spring, but there are only two commonly used methods: 1. use regular expression 2. I am not very familiar with the AspectJ expression (I am also familiar with it ).

Party or proficient party ?), I am still used to regular expressions.

Spring uses org. springframework. aop. support. JdkRegexpMethodPointcut to define the knots of regular expressions.
<Bean id = "spleepPointcut" class = "org. springframework. aop. support. JdkRegexpMethodPointcut">
<Property name = "pattern" value = ". * sleep"/>
</Bean>

The pattern attribute specifies a regular expression that matches all sleep methods.

The cut point only defines the location where the story occurred, the time when the story occurred, and the content of the most important story, that is, the notice. We need to combine the notice with the cut point, we want to use the following notification:
Org. springframework. aop. support. DefaultPointcutAdvisor

<Bean id = "sleepHelperAdvisor" class = "org. springframework. aop. support. DefaultPointcutAdvisor">
<Property name = "advice" ref = "sleepHelper"/>
<Property name = "pointcut" ref = "sleepPointcut"/>
</Bean>

The entry point and notification are configured. Next, call ProxyFactoryBean to generate a proxy object.

<Bean id = "humanProxy" class = "org. springframework. aop. framework. ProxyFactoryBean">
<Property name = "target" ref = "human"/>
<Property name = "interceptorNames" value = "sleepHelperAdvisor"/>
<Property name = "proxyInterfaces" value = "test. spring. aop. bean. Sleepable"/>
</Bean>

ProxyFactoryBean is a proxy. We can convert it to the proxy object specified in proxyInterfaces to implement this interface:

Import org. springframework. aop. framework. ProxyFactoryBean;
Import org. springframework. context. ApplicationContext;
Import org. springframework. context. support. ClassPathXmlApplicationContext;

Import test. spring. aop. bean. Sleepable;

Public class Test {

Public static void main (String [] args ){
ApplicationContext appCtx = new ClassPathXmlApplicationContext ("applicationContext. xml ");
Sleepable sleeper = (Sleepable) appCtx. getBean ("humanProxy ");
Sleeper. sleep ();
}
}

Result of running the program:
Usually, take off your clothes before going to bed!
Sleeping ~ You have your own face in your dream!
Wear clothes first after getting up!

OK! This is what we want, but the above process seems a bit complicated, especially when configuring the cut point and notification. Spring provides an automatic proxy function that allows automatic matching between the cut point and notification, modify the configuration file as follows:
<Bean id = "sleepHelper" class = "test. spring. aop. bean. SleepHelper">
</Bean>
<Bean id = "sleepAdvisor" class = "org. springframework. aop. support. RegexpMethodPointcutAdvisor">
<Property name = "advice" ref = "sleepHelper"/>
<Property name = "pattern" value = ". * sleep"/>
</Bean>
<Bean id = "human" class = "test. spring. aop. bean. Human">
</Bean>
<Bean class = "org. springframework. aop. framework. autoproxy. DefaultAdvisorAutoProxyCreator"/>

Execution program:
Public class Test {

Public static void main (String [] args ){
ApplicationContext appCtx = new ClassPathXmlApplicationContext ("applicationContext. xml ");
Sleepable sleeper = (Sleepable) appCtx. getBean ("human ");
Sleeper. sleep ();
}
}
The successful output result is the same as the previous one!
As long as we declare org. springframework. aop. framework. autoproxy. DefaultAdvisorAutoProxyCreator (which is too long for me), we can automatically create a proxy for the bean matching the method!

But there is still a lot of work to do. Is there a simpler way? Yes!

One way is to use the annotation provided by AspectJ:

Package test. mine. spring. bean;

Import org. aspectj. lang. annotation. AfterReturning;
Import org. aspectj. lang. annotation. Aspect;
Import org. aspectj. lang. annotation. Before;
Import org. aspectj. lang. annotation. Pointcut;
@ Aspect
Public class SleepHelper {

Public SleepHelper (){

}

@ Pointcut ("execution (**. sleep ())")
Public void sleeppoint (){}

@ Before ("sleeppoint ()")
Public void beforeSleep (){
System. out. println ("Take off your clothes before going to bed! ");
}

@ AfterReturning ("sleeppoint ()")
Public void afterSleep (){
System. out. println ("Wake up and wear clothes! ");
}

}

Use the @ Aspect annotation to identify the cut surface. Do not miss it. Otherwise, it will not be found when Spring creates a proxy, and the @ Pointcut annotation specifies the cut point, @ Before and @ AfterReturning specify the runtime notification. Note:

It indicates the name of the vertex to be input in the annotation.

Then, we need to work on the Spring configuration file. First, we need to add the XML namespace of AOP and declare the relevant schema.
Namespace:
Xmlns: aop = "http://www.springframework.org/schema/aop"
Schema statement:
Http://www.springframework.org/schema/aop
Http://www.springframework.org/schema/aop/spring-aop-2.0.xsd

Then add this label:
<Aop: aspectj-autoproxy/> with this Spring, the sections marked by @ Aspect can be automatically scanned.

Finally, it is easy to run:
Public class Test {

Public static void main (String [] args ){
ApplicationContext appCtx = new ClassPathXmlApplicationContext ("applicationContext. xml ");
Sleepable human = (Sleepable) appCtx. getBean ("human ");
Human. sleep ();
}
}

Next let's look at the last common method to implement AOP: Spring is used to define pure POJO aspect.

Previously we used the <aop: aspectj-autoproxy/> label. Spring also provides other configuration elements in the aop namespace:
<Aop: advisor> defines an AOP notifier
<Aop: after> post notification
<Aop: after-returning> post-return notification
<Aop: after-throwing> post-throw notification
<Aop: around> notifications
<Aop: aspect> define a plane
<Aop: before> pre-notification
<Aop: config> top-level Configuration elements, similar to <beans>
<Aop: pointcut> define a cut point

We use the AOP label to implement the sleeping process:
The Code remains unchanged. You only need to modify the configuration file and add the AOP Configuration:
<Aop: config>
<Aop: aspect ref = "sleepHelper">
<Aop: before method = "beforeSleep" pointcut = "execution (**. sleep (...)"/>
<Aop: after method = "afterSleep" pointcut = "execution (**. sleep (...)"/>
</Aop: aspect>
</Aop: config>

Complete!

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.