Spring AOP In-depth Anatomy

Source: Internet
Author: User
Tags throwable

first, through the proxy Factory mode configuration notification

①, pre-notification, post-notification:

Define an interface: Isomeservice and customize the method

public interface Isomeservice {public void Tran () throws Exception;        public void Log ();

Define the class to implement the interface, and override the Method:  

public class Someservice implements Isomeservice{public void Tran () throws Exception{system.out.println ("open transaction!! ");} public void log () {System.out.println ("logging!! ");}

Define the Pre-notification class and implement Methodbeforeadvice the interface

public class Mybefore implements Methodbeforeadvice{public void before (Method arg0, object[] arg1, Object Arg2) throws Thro Wable {System.out.println ("==before==");}

Define the Post-notification class and implement Afterreturningadvice the interface

public class Myafter implements Afterreturningadvice{public void afterreturning (Object arg0, Method arg1, object[] arg2,o Bject Arg3) throws Throwable {System.out.println ("==after==");}

To configure the spring configuration file Applicationcontext.xml:

Agent Factory: Proxyfactorybean

Test class :

Implementation Results:

② Surround Notification Methodinterceptor

Surround enhancement can be woven into the enhancement process before and after the target Method. Surround enhancement is the most powerful and powerful processing. Spring gave him all the control over the target Method. In Surround-enhancement processing, you can get or modify the parameters of a target method, return a value, treat it with exception, or even determine whether the target method Executes. 

To configure the spring file:

   <!--surround enhancement--   <bean id= "some" class= "cn.happy.entity.SomeService" ></bean>        <bean id= " Arround "class=" cn.happy.arround.MyInterceptor "></bean>    <bean id=" Factory "class=" Org.springframework.aop.framework.ProxyFactoryBean ">   <property name=" target "ref=" some "></ property>   <property name= "interceptornames" value= "arround" ></property> </bean>  

Implementation Results:

Surround enhancement is achieved through the Methodinterceptor interface. This interface requires the implementation of the Invoke () method, whose parameter methodinvocation not only encapsulates the target method and its parameter group, but also encapsulates the proxy target Object. The proceed () method can be used to invoke the corresponding method of the target object to achieve full control of the target method!

③ Exception Notification:

The feature is to weave in the enhanced processing when the target method throws an Exception. Exception-throwing enhancements are implemented through the Throwsadvice interface, but no methods are defined in the Throwsadvice interface, but we must adhere to the following method signature when defining the enhancement method thrown by the Exception:

void afterthrowing ([Method method,object[]arguments,object target,] throwable Ex)

In case of an exception to the implementation class:

Spring Configuration File:

<!--exception notifications-   <bean id= "some" class= "cn.happy.entity.SomeService" ></bean>         <bean id= " Throws "class=" cn.happy.throwsAdvice.MyThrows "></bean>    <bean id=" Factory "class=" Org.springframework.aop.framework.ProxyFactoryBean ">   <property name=" target "ref=" some "></ property>   <property name= "interceptornames" value= "throws" ></property> </bean>

Test Class:  

If the exception is thrown to the superior processing, in the console pass, single prediction error, If the exception is manually thrown, the contrary

@Testpublic void proxytest () {applicationcontext ctx=new classpathxmlapplicationcontext ("applicationcontext.xml"); Someservice ser= (isomeservice) ctx.getbean ("factory");//ser.tran ();    Try {ser.tran ();} catch (Exception e) {e.printstacktrace ();}    Ser.log ();}

 

second, Advisor Advisor

Advisor Advisor is another facet provided by Spring. It can be used to perform more complex facets weaving functions. Pointcutadvisor is one of the advisors that can specify a specific entry Point. The consultant wraps the notice and weaves the slices into different pointcuts at different points in time, depending on the type of Notification.
the Pointcutadvisor interface has two more commonly used implementation classes :
*:namematchmethodpointcutadvisor name matching method pointcut Consultant
*: regexpmethodpointcutadvisor Regular Expression matching method Entry-point Advisor
<property name= "pattern" value= ". *do.*" ></property> means full name (package name, interface name, method Name)
Operator name Meaning:
. The dot number represents any single character
+ PLUS sign indicates one or more occurrences of the previous character
* Asterisks indicate that the previous character appears 0 or more times

How to Achieve:

Similarly: define interfaces and implementation classes, and customize METHODS. and pre-enhanced Classes. Key points in spring configuration file

① name matching method pointcut Consultant

② regular Expression matching method Entry-point Advisor

third, Automatic Agent Generator

Note: The default Advisor auto Proxy generator, slices can only be consultants, and all objects are enhanced

Two ways to achieve this:

① default Advisor Auto Agent Builder Defaultadvisorautoproxycreator

②beanname Automatic Proxy Generator Beannameautoproxycreator

There is no need to configure the Agent factory bean, the ID of the test class Getbean () is the proxy object of the configuration file

The facet can only be a consultant case:

implementation Results:

Can be either a notification or a consultant case:

Implementation Results:

Test Class:

public class Test01 {@Testpublic void Proxytest () {applicationcontext ctx=new classpathxmlapplicationcontext (" Applicationcontext.xml "), isomeservice ser= (isomeservice) ctx.getbean (" some "); ser.tran ()     ; Ser.log ();}

 

four, Spring's Classic AOP configuration scheme, using the AspectJ third-party framework, realize the AOP Idea. Annotated configuration of aop, pure Pojo <aop:config>

Specific steps:
① adding springaop-related jar files to your project

② using annotations to define Pre-and post-enhancements for logging functions

③ writing spring configuration files, weaving annotation definition Enhancements

④ writing code to get business objects with enhanced processing

Core Jar Package:

Implementation Ideas:

1, define the interface implementation class, and override the method

public interface isomeservice {public void list ();}
public class Someservice implements isomeservice{public void list () {System.out.println ("someservice.list ()");}}

2. Enhanced by annotations, custom classes

The class is defined as a tangent using the @aspect annotation, and the method is defined as a predecessor enhancement using the @before annotation, and after the enhancement is defined, it is possible to weave in the spring configuration file the enhancements that use the annotation definition

@Aspectpublic class MYASPECTJ {@Before (value = "execution" (* *). Service.*.* (..)) ") public void Mybeforeadvice () {System.out.println ("==before==");}}

3. Spring configuration file

4, to Test:

public class Test01 {@Testpublic void Proxytest () {applicationcontext ctx=new classpathxmlapplicationcontext (" Applicationcontext.xml "), isomeservice ser= (isomeservice) ctx.getbean (" some "); ser.list ();}

Implementation Results:

※※※ additional Points:

Pointcut expression:
Execution ("modifiers-pattern?" access modifier
Ret-type-pattern return value type
"declaring-type-pattern?" fully qualified class name
Name-pattern (param-pattern) Method Name (parameter Name) Package Name. Name of the Type. method name
"throws-pattern") throws Exception type


public void Dolog (String Log) {

}

The object that the Pointcut expression matches is the method name of the target Method. therefore, the execution expression is clearly the signature of the Method.

Note : The part of the expression that adds [] can be omitted, separated by a space between the Sections. The following symbols can be used in them:
Symbolic meanings:
* 0 to any number of characters
.. Used in method parameters to represent any number of arguments
Used after the package name to represent the current package and its child package path
+ used after the class name to represent the current class and its subclasses
After the interface, it represents the current interface and its implementation class
Case:
Execution (public * * (..)) Specifies the pointcut as: any common method
Execution (* set* (..)) Specifies the Pointcut as: any method starting with "set"

Spring AOP In-depth Anatomy

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.