Spring AOP (aspect-oriented programming) framework for crosscutting concerns in modularity. Simply put, it's just an interceptor that intercepts some process, for example, when a method executes, Spring AOP can hijack an execution method, adding additional functionality before or after the method executes. In spring AOP, there are 4 types of notification (advices) support:
- Notification (Advice) before-the method is run before execution
- After the notification (Advice) is returned – after running, the method returns a result
- After the notification (Advice) is thrown – after the Run method throws an exception,
- Surround Notification – The surround method performs the operation, combined with these three notifications.
The following example shows how spring AOP notifications work. The simple Spring example creates a simple customer service class and a print method as a demonstration.
Package Com.yiibai.customer.services;public class CustomerService {private string name;private string url;public void SetName (String name) {this.name = name;} public void SetUrl (String url) {this.url = URL;} public void Printname () {System.out.println ("Customer name:" + this.name);} public void Printurl () {System.out.println ("Customer website:" + this.url);} public void Printthrowexception () {throw new IllegalArgumentException ();}}
file:applicationcontext.xml– A bean configuration file
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xsi:schemalocation=" http://www.springframework.org/schema/beanshttp:// Www.springframework.org/schema/beans/spring-beans-2.5.xsd "><bean id=" CustomerService "class=" Com.yiibai.customer.services.CustomerService "><property name=" name "value=" Yiibaii Mook Kim "/>< Property name= "url" value= "http://www.yiibai.com"/></bean></beans>
Execute it
Package Com.yiibai.common;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.yiibai.customer.services.customerservice;public class App {public static void main (string[] args) { ApplicationContext appContext = new Classpathxmlapplicationcontext (new string[] {"Spring-customer.xml"}); CustomerService cust = (customerservice) appcontext.getbean ("CustomerService"); System.out.println ("*************************"); Cust.printname (); System.out.println ("*************************"); Cust.printurl (); System.out.println ("*************************"); try {cust.printthrowexception ();} catch (Exception e) {}}}
Output
Customer Name:yiibai Mook Kim*************************customer website:http:// www.yiibai.com*************************
A simple spring project is used to inject (DI) beans and output some strings. Spring AOP notification Now, additional spring AOP is recommended to the above customer service. 1. Before notifying it that it will be executed before the method executes. Create a class that implements the Methodbeforeadvice interface.
Package Com.yiibai.aop;import Java.lang.reflect.method;import Org.springframework.aop.methodbeforeadvice;public Class Hijackbeforemethod implements methodbeforeadvice{@Overridepublic void before (method, object[] args, Object Target) throws Throwable { System.out.println ("Hijackbeforemethod:before method hijacked!");}}
In the bean configuration file (applicationcontext.xml), create a bean's Hijackbeforemethod class and name "Customerserviceproxy" as a new proxy object.
- ' Target ' – define the bean you want to intercept.
- ' Interceptornames ' – Defines the class (notification) to which this proxy/target object is to be applied.
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xsi:schemalocation=" Http://www.springframework.org/schema/beans/ http Www.springframework.org/schema/beans/spring-beans-2.5.xsd "><bean id=" CustomerService "class=" Com.yiibai.customer.services.CustomerService "><property name=" name "value=" Yiibai Mook Kim "/><property Name= "url" value= "http://www.yiibai.com"/></bean><bean id= "Hijackbeforemethodbean" class= " Com.yiibai.aop.HijackBeforeMethod "/><bean id=" Customerserviceproxy " class=" Org.springframework.aop.framework.ProxyFactoryBean "><property name=" target "ref=" CustomerService "/>< Property Name= "Interceptornames" ><list><value>hijackBeforeMethodBean</value></list> </property></bean></beans>
Run it again and now get the new customerserviceproxy bean instead of the original CustomerService bean.
Package Com.yiibai.common;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.yiibai.customer.services.customerservice;public class App {public static void main (string[] args) { ApplicationContext appContext = new Classpathxmlapplicationcontext (new string[] {"Spring-customer.xml"}); CustomerService cust = (customerservice) Appcontext.getbean ("Customerserviceproxy"); System.out.println ("*************************"); Cust.printname (); System.out.println ("*************************"); Cust.printurl (); System.out.println ("*************************"); try {cust.printthrowexception ();} catch (Exception e) {}}}
Output results
Hijackbeforemethod:before Method hijacked! Customer Name:yiibai Mook Kim*************************hijackbeforemethod:before method hijacked! Customer Website:http://www.yiibai.com*************************hijackbeforemethod:before Method hijacked!
It will run Hijackbeforemethod's before () method, which is executed before each CustomerService method. 2. When returned, notifies the method that it will execute after returning a result. Create a class that implements the Afterreturningadvice interface.
Package Com.yiibai.aop;import Java.lang.reflect.method;import Org.springframework.aop.afterreturningadvice;public Class Hijackaftermethod implements afterreturningadvice{@Overridepublic void afterreturning (Object returnvalue, Method method,object[] args, Object target) throws Throwable { System.out.println ("Hijackaftermethod:after method H Ijacked! ");}}
Bean configuration file
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xsi:schemalocation=" Http://www.springframework.org/schema/beans/ http Www.springframework.org/schema/beans/spring-beans-2.5.xsd "><bean id=" CustomerService "class=" Com.yiibai.customer.services.CustomerService "><property name=" name "value=" Yong Mook Kim "/><property Name= "url" value= "http://www.yiibai.com"/></bean><bean id= "Hijackaftermethodbean" class= " Com.yiibai.aop.HijackAfterMethod "/><bean id=" Customerserviceproxy " class=" Org.springframework.aop.framework.ProxyFactoryBean "><property name=" target "ref=" CustomerService "/>< Property Name= "Interceptornames" ><list><value>hijackAfterMethodBean</value></list> </property></bean></beans>
Run again, output
Customer Name:yiibai Mook Kimhijackaftermethod:after method hijacked!********************* Customer Website:http://www.yiibai.comhijackaftermethod:after Method hijacked!*************************
It will run Hijackaftermethod's afterreturning () method, after each CustomerService method returns the result. 3. After the throw notification it will be thrown after the execution method throws an exception. Create a class that implements the Throwsadvice interface and create a afterthrowing method to intercept the thrown: IllegalArgumentException exception.
Package Com.yiibai.aop;import Org.springframework.aop.throwsadvice;public class Hijackthrowexception implements Throwsadvice {public void afterthrowing (IllegalArgumentException e) throws Throwable {System.out.println (" Hijackthrowexception:throw exception hijacked! ");}}
Bean configuration file
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xsi:schemalocation=" Http://www.springframework.org/schema/beans/ http Www.springframework.org/schema/beans/spring-beans-2.5.xsd "><bean id=" CustomerService "class=" Com.yiibai.customer.services.CustomerService "><property name=" name "value=" Yong Mook Kim "/><property Name= "url" value= "http://www.yiibai.com"/></bean><bean id= "Hijackthrowexceptionbean" class= " Com.yiibai.aop.HijackThrowException "/><bean id=" Customerserviceproxy " class=" Org.springframework.aop.framework.ProxyFactoryBean "><property name=" target "ref=" CustomerService "/>< Property Name= "Interceptornames" ><list><value>hijackthrowexceptionbean</value></list ></property></bean></beans>
Run again, output
Customer Name:yiibai Mook Kim*************************customer website:http:// Www.yiibai.com*************************hijackthrowexception:throw Exception hijacked!
It will run the Hijackthrowexception afterthrowing () method if the CustomerService method throws an exception. 4. Surround Notifications
It combines the three notifications above and executes during the execution of a method. Create a class that implements the Methodinterceptor interface. You must call "Methodinvocation.proceed ();" To continue executing in the original method, otherwise the original method will not execute.
Package Com.yiibai.aop;import Java.util.arrays;import Org.aopalliance.intercept.methodinterceptor;import Org.aopalliance.intercept.methodinvocation;public class Hijackaroundmethod implements Methodinterceptor {@ Overridepublic Object Invoke (Methodinvocation methodinvocation) throws Throwable {System.out.println ("Method Name:" + Methodinvocation.getmethod (). GetName ()); System.out.println ("Method arguments:" + arrays.tostring (methodinvocation.getarguments ()));//Same with MethodBeforeAdviceSystem.out.println ("Hijackaroundmethod:before method hijacked!"); try {//Proceed to original method CallObject result = Methodinvocation.proceed (),//Same with Afterreturningadvicesystem. Out.println ("Hijackaroundmethod:before after hijacked!"); return result;} catch (IllegalArgumentException e) {//Same with THROWSADVICESYSTEM.OUT.PRINTLN ("Hijackaroundmethod:throw exception Hijacked! "); throw e;}}}
Bean configuration file
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xsi:schemalocation=" Http://www.springframework.org/schema/beans/ http Www.springframework.org/schema/beans/spring-beans-2.5.xsd "><bean id=" CustomerService "class=" Com.yiibai.customer.services.CustomerService "><property name=" name "value=" Yong Mook Kim "/><property Name= "url" value= "http://www.yiibai.com"/></bean><bean id= "Hijackaroundmethodbean" class= " Com.yiibai.aop.HijackAroundMethod "/><bean id=" Customerserviceproxy " class=" Org.springframework.aop.framework.ProxyFactoryBean "><property name=" target "ref=" CustomerService "/>< Property Name= "Interceptornames" ><list><value>hijackAroundMethodBean</value></list> </property></bean></beans>
Run again, output
Method name:printnamemethod Arguments: []hijackaroundmethod:before method hijacked! Customer Name:yiibai Mook Kimhijackaroundmethod:before after Hijacked!*************************method NAME:PRINTURLM Ethod arguments: []hijackaroundmethod:before method hijacked! Customer website:http://www.yiibai.com Hijackaroundmethod:before after Hijacked!*************************method Name:printthrowexceptionmethod arguments: []hijackaroundmethod:before method hijacked! Hijackaroundmethod:throw Exception hijacked!
It will run Hijackaroundmethod's Invoke () method after each CustomerService method executes. Summing up most of the Spring developers just implement "surround notification" because it can be for all types of notifications, but a better approach should be to choose the most appropriate notification type to meet the requirements. Pointcut in this example, all methods in a customer service class are automatically intercepted (notified). In most cases, however, you may need to use pointcuts and advisors to intercept its methods by its method name. Download Code –
Spring AOP Notification Instance –advice