When we configure the IOC functionality, we implement the configuration file XML and annotations in two ways. There are two ways we can use it when implementing AOP functionality. Earlier, we described the implementation of AOP based on annotations, which I will use in the configuration file-based approach to the configuration of the original object bean, slice bean, tangent, and notification.
Declaring slices with an XML-based configuration
In addition to using AspectJ annotations to declare facets, Spring also supports declaring facets in a Bean configuration file. This declaration is done through the XML elements in the AOP schema.
Under normal circumstances, annotation-based declarations take precedence over XML-based declarations. With AspectJ annotations, facets can be compatible with AspectJ, whereas XML-based configuration is Spring proprietary. Because AspectJ is supported by an increasing number of AOP frameworks, facets written in annotation style will have more opportunities for reuse.
Well, let's talk about it in an example. We re-build a package that builds core business classes and slicing classes:
Core class: Subtraction Computing
Slice 1: Data validation
Tangent 2: Output log
package com.happbks.spring.aopbasic.aop2;public class AtithmeticCalculateImpl implements AtithmeticCalculate {public int Add (Int a, int b) {int result=a+b;return result;} Public int sub (Int a, int b) {int result=a-b;return result;} Public int mul (Int a, int b) {int result=a*b;return result;} Public int div (Int a, int b) {int result=a/b;return result;}}
package com.happbks.spring.aopbasic.aop2;public class AtithmeticCalculateImpl implements AtithmeticCalculate {public int Add (Int a, int b) {int result=a+b;return result;} Public int sub (Int a, int b) {int result=a-b;return result;} Public int mul (Int a, int b) {int result=a*b;return result;} Public int div (Int a, int b) {int result=a/b;return result;}}
package com.happbks.spring.aopbasic.aop2;import java.util.arrays;import java.util.list;import org.aspectj.lang.joinpoint;public class datavalidateaspect {public boolean beforemethod (Joinpoint joinpoint) {String Methodname=joinpoint.getsignature (). GetName (); List<object> args=arrays.aslist (Joinpoint.getargs ()); System.out.println ("Data validate---begin to " +methodname+ " with " +args "); if ((Integer) (Args.get (0)) >0&& (Integer) (Args.get (1)) >0) {System.out.println ("Data is ok"); return true;} Else{system.out.println ("Data is bad"); return false;}}
Package com.happbks.spring.aopbasic.aop2;import java.util.arrays;import java.util.list;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;public class loggingaspect {/* * executes before each method of each implementation class of the Com.happBKs.spring.aopbasic.aop1.AtithmeticCalculate interface starts */public void beforemethod (joinpoint joinpoint) {string methodname= Joinpoint.getsignature (). GetName (); List<object> args=arrays.aslist (Joinpoint.getargs ()); System.out.println ("begin to " +methodname+ " with " +args);} /* * after the target method executes (whether or not an exception occurs), execute the notification */public void aftermethod (joinpoint joinpoint) { String methodname=joinpoint.getsignature (). GetName (); System.out.println ("end to " +methodname); /* * Code * return notification that executes after the target method has been executed normally is */public void afterreturning that can access the return value of the target method ( Joinpoint joinpoint, object resultparam) {STRING&NBSP;METHODNAME=JOINPOint.getsignature (). GetName (); System.out.println ("after " +methodname+ " with returning result " +resultparam);} /* * code * can access the exception object when an exception occurs in the target method, and can specify that code is executed at a specific exception */public void Afterthrowing (joinpoint joinpoint, exception exthrowing) {string methodname= Joinpoint.getsignature (). GetName (); System.out.println ("after exception of " +methodname+ " we find the exception is "+exthrowing);} /* * loopback notifications need to carry Proceedingjoinpoint type parameters * Loopback notifications are similar to the whole process of dynamic agents: Parameters of the Proceedingjoinpoint type can determine whether to execute the target method * and the loopback notification must have a return value, which is the return value of the target method */public Object roundingmethod (PROCEEDINGJOINPOINT&NBSP;PJP) {object result=null; String methodname=pjp.getsignature (). GetName () try {//Pre-notification System.out.println ("Around: begin method "+methodname+" executed with "+arrays.aslist (Pjp.getargs ()));result= Pjp.proceed ();//Return Notification System.out.println ("ArOund: return method "+methodname+" with result "+result);} catch (throwable e) {// TODO Auto-generated catch Blocke.printstacktrace ();//Exception Notification System.out.println ("around: exception in " +methodname+ ":" +e );} Post-Notification System.out.println ("Around: end method" +methodname); return 100;}}
Above these classes, we no longer need to add a variety of annotations, all facets, notifications, pointcuts, etc. we are configured in the configuration file:
New configuration file Applicationcontext-xml.xml. (Join beans and AOP namespaces)
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/ Schema/beans "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xmlns:aop=" http://www.springframework.org/ Schema/aop "xsi:schemalocation=" http://www.springframework.org/schema/beans http://www.springframework.org /schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/ Schema/aop/spring-aop-4.1.xsd "><!-- Configure bean --><bean id=" Atithmeticcalculate "class=" Com.happBKs.spring.aopbasic.aop2.AtithmeticCalculateImpl "></bean><!-- configuration facets bean --> <bean id= "Datavalidateaspect" class= "Com.happBKs.spring.aopbasic.aop2.DataValidateAspect" >< /bean><bean id= "Loggingaspect" class= "Com.happBKs.spring.aopbasic.aop2.LoggingAspect" ></ bean><!-- Configure aop --><aop:config><!-- Configure pointcut Expressions --><aop:pointcut Id= "Pointcutdata" expression= "Execution (* com.happbks.spring.aopbasic.aop2.atithmeticcalculateimpl.* (..))" /><!-- Configuration facets and notifications --><aop:aspect ref= "Datavalidateaspect" order= "2" >< Aop:before method= "Beforemethod" pointcut-ref= "Pointcutdata" &NBSP;/></AOP:ASPECT><AOP: aspect ref= "Loggingaspect" order= "1" ><aop:before method= "Beforemethod" pointcut-ref= "Pointcutdata" /><aop:after method= "Aftermethod" pointcut-ref= "PointCutData"/><AOP: After-throwing method= "afterthrowing" pointcut-ref= "Pointcutdata" throwing= "exThrowing"/> <aop:after-returning method= "afterreturning" pointcut-ref= "Pointcutdata" returning= " Resultparam "/><aop:around method=" Roundingmethod " pointcut-ref=" PointCutData " /></ Aop:aspect></aop:config></beans>
Here are the steps:
1, first configure all the original object's beans.
2, then configure all the slice beans, configure the bean ID of the slice to map the slice class.
3, configuring AOP
(1) Configure tangency point: A notification that relates to which methods are executed when the relevant facets are called. The tangent is configured first, and a reference is kept for a while.
(2) Configure each facet:
A. Configures the mapping of the slice Bean's ID to the order plane priority, and the individual notifications within the slice.
B. Configures the mapping of notifications and pointcuts within individual facets, and the pointcut is given as a reference.
Test code:
package com.happbks.spring.aopbasic;import org.junit.test;import org.springframework.context.applicationcontext;import org.springframework.context.support.classpathxmlapplicationcontext;import com.happbks.spring.aopbasic.aop2.atithmeticcalculate;public class testspringaop2 {@Testpublic &NBSP;VOID&NBSP;TESTSPRINGAOP () {//1. Create a spring IOC container applicationcontext ac=new Classpathxmlapplicationcontext ("Applicationcontext-xml.xml");//2. gets the bean instance from the IOC container atithmeticcalculate atithmeticcalculate = (atithmeticcalculate) Ac.getbean (atithmeticcalculate.class);// Examine whether the proxy object generates SYSTEM.OUT.PRINTLN (Atithmeticcalculate.getclass (). GetName ());//3. use BeanSystem.out.println (" Example 1: "); Int result=atithmeticcalculate.add (10, 5); SYSTEM.OUT.PRINTLN (result); System.out.println ("\r\nexample 2:"); Int result2=atithmeticcalculate.div (10, 0); System.out.println (RESULT2);}}
Operation Result:
Com.sun.proxy. $Proxy 4
Example 1:
Begin to add with [10, 5]
Around:begin Methodadd executed with [10, 5]
Data Validate---Begin to add with [10, 5]
Data is OK
Around:return Methodadd with result15
Around:end Methodadd
After add with returning result 100
End to add
100
Example 2:
Begin to Div with [10, 0]
Around:begin Methoddiv executed with [10, 0]
Data Validate---Begin to div with [10, 0]
Data is bad
Java.lang.ArithmeticException:/By zero
at Com.happBKs.spring.aopbasic.aop2.AtithmeticCalculateImpl.div (atithmeticcalculateimpl.java:24)
at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at Sun.reflect.NativeMethodAccessorImpl.invoke (Unknown Source)
at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Unknown Source)
at Java.lang.reflect.Method.invoke (Unknown Source)
at Org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection (aoputils.java:317)
at Org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint ( reflectivemethodinvocation.java:190)
at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( reflectivemethodinvocation.java:157)
at Org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke ( METHODBEFOREADVICEINTERCEPTOR.JAVA:52)
at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( reflectivemethodinvocation.java:179)
at Org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed ( METHODINVOCATIONPROCEEDINGJOINPOINT.JAVA:85)
at Com.happBKs.spring.aopbasic.aop2.LoggingAspect.roundingMethod (loggingaspect.java:76)
at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at Sun.reflect.NativeMethodAccessorImpl.invoke (Unknown Source)
at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Unknown Source)
at Java.lang.reflect.Method.invoke (Unknown Source)
at Org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs ( abstractaspectjadvice.java:621)
at Org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod (Abstractaspectjadvice.java : 610)
at Org.springframework.aop.aspectj.AspectJAroundAdvice.invoke (aspectjaroundadvice.java:68)
at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( reflectivemethodinvocation.java:179)
at Org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke ( AFTERRETURNINGADVICEINTERCEPTOR.JAVA:52)
at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( reflectivemethodinvocation.java:179)
at Org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke (Aspectjafterthrowingadvice.java : 58)
at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( reflectivemethodinvocation.java:179)
at Org.springframework.aop.aspectj.AspectJAfterAdvice.invoke (aspectjafteradvice.java:43)
at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( reflectivemethodinvocation.java:179)
at Org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke ( METHODBEFOREADVICEINTERCEPTOR.JAVA:52)
at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( reflectivemethodinvocation.java:179)
at Org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke ( exposeinvocationinterceptor.java:92)
at Org.springframework.aop.framework.ReflectiveMethodInvocation.proceed ( reflectivemethodinvocation.java:179)
at Org.springframework.aop.framework.JdkDynamicAopProxy.invoke (jdkdynamicaopproxy.java:207)
at Com.sun.proxy. $Proxy 4.div (Unknown Source)
at Com.happBKs.spring.aopbasic.TestSpringAOP2.testSpringAOP (testspringaop2.java:24)
at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at Sun.reflect.NativeMethodAccessorImpl.invoke (Unknown Source)
at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Unknown Source)
at Java.lang.reflect.Method.invoke (Unknown Source)
at Org.junit.runners.model.frameworkmethod$1.runreflectivecall (frameworkmethod.java:45)
at Org.junit.internal.runners.model.ReflectiveCallable.run (reflectivecallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively (frameworkmethod.java:42)
at Org.junit.internal.runners.statements.InvokeMethod.evaluate (invokemethod.java:20)
at Org.junit.runners.ParentRunner.runLeaf (parentrunner.java:263)
at Org.junit.runners.BlockJUnit4ClassRunner.runChild (blockjunit4classrunner.java:68)
at Org.junit.runners.BlockJUnit4ClassRunner.runChild (blockjunit4classrunner.java:47)
at Org.junit.runners.parentrunner$3.run (parentrunner.java:231)
at Org.junit.runners.parentrunner$1.schedule (parentrunner.java:60)
at Org.junit.runners.ParentRunner.runChildren (parentrunner.java:229)
at org.junit.runners.parentrunner.access$000 (parentrunner.java:50)
at Org.junit.runners.parentrunner$2.evaluate (parentrunner.java:222)
at Org.junit.runners.ParentRunner.run (parentrunner.java:300)
at Org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run (junit4testreference.java:50)
at Org.eclipse.jdt.internal.junit.runner.TestExecution.run (testexecution.java:38)
at Org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests (remotetestrunner.java:459)
at Org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests (remotetestrunner.java:675)
at Org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run (remotetestrunner.java:382)
at Org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main (remotetestrunner.java:192)
Around:exception in Div:java.lang.ArithmeticException:/by zero
Around:end Methoddiv
After div with returning result 100
End to Div
100
Spring Framework Notes (23)--Configuring AOP based on configuration files