4 ways in which spring implements AOP

Source: Internet
Author: User

Learn about the terminology related to AOP first:
1. Notice (Advice):
Notifications define what facets are and when to use them. Describes the work to be done on the slice and when it is necessary to perform the work.
2. Connection point (Joinpoint):
A program can apply a "timing" of notifications, which are connection points, such as when a method is invoked, when an exception is thrown, and so on.
3. Entry point (Pointcut)
The notification defines the "story" and the time that the slice will take place, and the pointcut defines where the "story" takes place, such as the name of a class or method, which in spring allows us to use the regular expression easily to specify
4. Facets (Aspect)
Notifications and pointcuts form a slice: time, place, and "story" to take place
5. Introduction (Introduction)
Introduction allows us to add new methods and properties to existing classes (spring provides a way to inject functionality)
6. Goal (target)
The object that is notified, if there is no AOP, then its logic will cross other transactional logic, and with AOP it can only focus on what it wants to do (AOP lets him make Love)
7. Agent (proxy)
The object for which notifications are applied, see Proxy mode in design mode for details
8. Weave in (Weaving)
The process of applying facets to a target object to create a new proxy object usually occurs in the following time:
(1) Compile time: When a class file is compiled, this requires a special compiler to do so, such as AspectJ's weaving compiler
(2) class loading: Use special ClassLoader to enhance the class's byte code before the target class is loaded into the program
(3) Run time: section at a time of operation is woven into, SPRINGAOP is in this way to weave into the plane, the principle should be the use of the JDK dynamic agent technology

Spring offers 4 ways to implement AOP:
1. Classic Agent-based AOP
[Email protected] annotation-driven facets
3. Pure Pojo Facets
4. Injection-type ASPECTJ facets

First look at the classic agent-based AOP:
Spring supports five types of notifications:
Before (ex) Org.apringframework.aop.MethodBeforeAdvice
After-returning (after return) Org.springframework.aop.AfterReturningAdvice
After-throwing (after throw) Org.springframework.aop.ThrowsAdvice
Arround (around) org.aopaliance.intercept.MethodInterceptor
Introduction (introduced) org.springframework.aop.IntroductionInterceptor

The description of the value is the surrounding notification, which is defined by the interface in the AOP Alliance rather than spring, and the surrounding notification is equivalent to the combination of the previous notification, the notification after the return, and the notification after the throw (the legendary complete body? Well, I look at the day and see more

) and the introduction of the notice how to play I have not figured out, waiting for the heart to play without distractions

How do you play this thing? So several steps:
1. Create a notification: implement these interfaces and implement the methods
2. Defining Pointcuts and Notifier: Configure this information in the spring configuration file
3. Using Proxyfactorybean to generate agents

Concrete Practice ... For the big night, let's take a bedtime example:

First write an interface called Sleepable, which is a cow x interface, all sleep-capable things can implement the interface (not only mobs, including sleep in the shutdown option)

Package Test.spring.aop.bean

public interface sleepable{

void Sleep ();
}

Then write a human class, and he implements this interface

Package Test.spring.aop.bean

Public Human implements sleepable{

* * Is this person similar to my own?
* Besides sleeping well, the rest is not going to do anything? */
public void sleep () {
SYSTEM.OUT.PRINTLN ("Sleep! Dream of own Yanruyu! ");
}

}


Well, this is the main character, but to do some auxiliary work before and after sleep, the most basic is to undress, insomnia people also have to eat sleeping pills or something, but these actions and pure sleep this "business logic" is irrelevant, if the

Is it not a single duty to add all of this code to the Sleep method? , then we need AOP.

Write a Sleephelper class, which contains the auxiliary work of sleeping, in terms of AOP 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 ("Always take off your clothes before you go to bed!") ");
}

public void afterreturning (Object arg0, Method arg1, object[] arg2,
Object Arg3) throws Throwable {
System.out.println ("Get dressed before you wake up!") ");
}

}

Then configure it in the Spring configuration file:
<bean id= "Sleephelper" class= "Test.spring.aop.bean.SleepHelper" >
</bean>

ok! now the job of creating the notification is complete.

The second step is to make the configuration, which is very painful operation, especially so hot day, spring again the name of the thing to the heck of a long! Why can't it be like USR's style?

The first thing to do is to configure a tangent point, which is said to be represented in spring in several ways, but there are only two common: 1. Using regular Expressions 2. Using the ASPECTJ expression AspectJ I'm not very familiar with it.

Party or proficient in the party? ), I'm still accustomed to using regular expressions

Spring uses Org.springframework.aop.support.JdkRegexpMethodPointcut to define a regular expression pointcut
<bean id= "Spleeppointcut" class= "Org.springframework.aop.support.JdkRegexpMethodPointcut" >
<property name= "pattern" value= ". *sleep"/>
</bean>

The Pattern property specifies a regular expression that matches all sleep methods

The pointcut simply defines where the story takes place, the time of the story and the most important story, that is, notice that we need to combine the notice with the pointcut, the notifier we are using:
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>

Both the pointcut and the notification are configured, and then the call Proxyfactorybean generates the 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 that we can convert to the proxy object specified in Proxyinterfaces to implement the 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 ();
}
}

The program runs to produce the result:
Always undress before you go to bed!
Sleep ~ Dream of own Yanruyu!
Get up and dress first!

Ok! This is the result we want, but the above process seems a bit complicated, especially with the configuration of pointcuts and notifications, Spring provides an automatic proxy function that allows the pointcut to match the notification automatically and 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"/>

Execute the program:
public class Test {

public static void Main (string[] args) {
ApplicationContext appctx = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
Sleepable sleeper = (sleepable) Appctx.getbean ("Human");
Sleeper.sleep ();
}
}
Successful output results in front of the same!
As long as we declare the Org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator (I have gone, the name is too long) You can automatically create proxies for method-matching beans!

But there is still a lot of work to be done, is there a simpler way?

One way is to use annotations 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 you go to bed!");
}

@AfterReturning ("Sleeppoint ()")
public void Aftersleep () {
System.out.println ("Wake up and get dressed!") ");
}

}

Use the @aspect annotation to identify the slice, and be careful not to leak it, or spring will not find it when creating the proxy, @Pointcut note Specifies the pointcut, @Before and @afterreturning specify the runtime notification, note

The name of the pointcut to be passed in the annotation

Then we work on the spring configuration file, first of all by adding an AOP XML namespace and declaring the relevant schema
Namespaces:
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 tag:
<aop:aspectj-autoproxy/> with this spring, you can automatically scan the slices that are @aspect labeled.

The last is the operation, very simple and convenient:
public class Test {

public static void Main (string[] args) {
ApplicationContext appctx = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
Sleepable human = (sleepable) Appctx.getbean ("Human");
Human.sleep ();
}
}

Let's take a look at the last common way to implement AOP: Using spring to define pure Pojo facets

We used the <aop:aspectj-autoproxy/> tag in front of it, and spring provides additional configuration elements in the AOP namespace:
<aop:advisor> Define an AOP notifier
Notification after <aop:after>
<aop:after-returning> Notification upon return
<aop:after-throwing> notification after throwing
<aop:around> around notifications
<aop:aspect> Define a slice
<aop:before> Pre-notification
<aop:config> top-level configuration elements, similar to <beans> this kind of thing
<aop:pointcut> Defining a tangent point

We use AOP tags to implement the process of sleeping:
The code does not change, just 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>

Finish!

Ok~~ basically so much, want to use good also have to toss toss, in addition to play aspectj~ is a play!

4 ways in which spring implements AOP

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.