java--Simple Spring AOP configuration and AOP things management, jdk/gclib dynamic proxy

Source: Internet
Author: User

First, take a look at the simple AOP configuration through XML

1. Start by creating a simple student class

 Public classStudent {PrivateInteger age; PrivateString name;  Public voidsetage (Integer age) { This. Age =Age ; }     PublicInteger getage () {System.out.println ("Age:" +Age ); returnAge ; }     Public voidsetName (String name) { This. Name =name; }     PublicString GetName () {System.out.println ("Name:" +name); returnname; }     Public voidprintthrowexception () {System.out.println ("Exception raised"); Throw Newillegalargumentexception (); }}

2. Create a simple aspect tangent class

 Public classLogging {/*** This is the method which I would like to execute * before a selected method execution. */ Public voidBeforeadvice () {System.out.println ("Going to setup student profile."); }    /*** This was the method which I would like to execute * After a selected method execution. */ Public voidAfteradvice () {System.out.println ("Student profile has been setup."); }    /*** This is the method which I would if any method returns. */     Public voidAfterreturningadvice (Object retVal) {System.out.println ("Returning:" +retval.tostring ()); }    /*** This is the method which I would like to execute * if there are an exception raised. */     Public voidAfterthrowingadvice (IllegalArgumentException ex) {System.out.println ("There have been an exception:" +ex.tostring ()); }}

3.springaop.xml Configuration

    <BeanID= "Student"class= "Com.seeyon.SpringBean.aop.Student"P:name= "Yangyu"P:age= "+"></Bean>    <BeanID= "Logging"class= "Com.seeyon.SpringBean.aop.Logging"></Bean>    <!--Configuring spring AOP in XML mode -    <Aop:config>        <Aop:aspectID= "Log"ref= "Logging"> "Tangent class"            <Aop:pointcutID= "Studentmethod"expression= "Execution (* com.seeyon.springbean.aop.student.get* (..))"/> "Tangent"            <Aop:beforePointcut-ref= "Studentmethod"Method= "Beforeadvice"/> The Beforeadvice method that triggers the slice class before the method executes            <Aop:afterPointcut-ref= "Studentmethod"Method= "Afteradvice"/> "Afteradvice method that triggers the slice class after the method executes "        </Aop:aspect>    </Aop:config>

Analyze This execution (* com.seeyon.springbean.aop.student.get* (..)) Tangent expression:

(1) The first * represents the return value of a method is arbitrary

(2) get* represents all methods that start with get

(3) (..) The parameter representing the method is any number

4.main method

 Public class Test {    publicstaticvoid  main (string[] args) {        =                New classpathxmlapplicationcontext ("Springaop.xml");         = (Student) context.getbean ("Student");        Student.getname (); //         student.getage (); //         student.printthrowexception ();     }}

5. Output results

Going to setup student profile. Name:yangyustudent profile has been setup.

Second, the use of Spring AOP annotations.

1. First create a simple student class (in the same. 1, see above??). )

2. Create a simple aspect tangent class with the @ annotation configuration.

@Aspect//Represents a Aspect tangent class that can be scanned by spring to Public classLogging {@Pointcut ("Execution (* com.seeyon.springbean.aop.student.get* (..))")//define Pointcuts Public voidGetMethod () {};//Tangent method, method name is equivalent to ID, method name is arbitrarily taken/*** This is the method which I would like to execute * before a selected method execution. */@Before ("GetMethod ()")//tangent method execution before executing @before Public voidBeforeadvice () {System.out.println ("Going to setup student profile."); }    /*** This was the method which I would like to execute * After a selected method execution. */@After ("GetMethod ()")//Tangent method executes after execution of @after Public voidAfteradvice () {System.out.println ("Student profile has been setup."); }    /*** This is the method which I would if any method returns. */@AfterReturning (pointcut= "GetMethod ()", returning = "RetVal")//Tangent method returns the value after completion of execution @afterreturning Public voidAfterreturningadvice (Object retVal) {System.out.println ("Returning:" +retval.tostring ()); }    /*** This is the method which I would like to execute * if there are an exception raised. */@AfterThrowing (pointcut= "GetMethod ()", throwing = "Ex")//The Pointcut method throws an exception after executing @afterthrowing Public voidAfterthrowingadvice (IllegalArgumentException ex) {System.out.println ("There have been an exception:" +ex.tostring ()); }}

3.springaop.xml Configuration

    <BeanID= "Student"class= "Com.seeyon.SpringBean.aop.Student"P:name= "Yangyu"P:age= "+"></Bean>    <BeanID= "Logging"class= "Com.seeyon.SpringBean.aop.Logging"></Bean>    <!--annotation Mode configuration Spring aop,spring automatically goes to the registered bean to find the class of the @aspect annotation tag -    <Aop:aspectj-autoproxy/>

4.mian method

 Public class Test {    publicstaticvoid  main (string[] args) {        =                New classpathxmlapplicationcontext ("Springaop.xml");         = (Student) context.getbean ("Student");        Student.getname (); //         student.getage (); //         student.printthrowexception ();     }}

5. Output results

Going to setup student profile. Name:yangyustudent profile has been setup. Returning:yangyu

Precautions:

<aop:config proxy-target-Class= "true" ></aop:config><aop:aspectj-autoproxy proxy-target- class= "true"/>

1. If you do not set the Proxy-target-class property or set it to false:

(1) The proxy class implements the interface, then AOP is actually the automatic proxy that uses the JDK, the proxy interface.

(2) The proxy class does not have an interface, then the cglib is used for proxy.

2. If you set the Proxy-target-class property to True, you will always use Cglib for proxy.

Dynamic differences between JDK dynamic agent and Cglib:

1, JDK dynamic Agent: The JDK dynamic proxy depends on the interface implementation, if some classes do not implement the interface, you can not use the JDK proxy, this will use Cglib dynamic proxy.

2, Cglib dynamic Agent: Cglib is for the class to implement the proxy, his principle is to create a subclass of the specified target class, and override the method implementation enhancements, but because of the inheritance, so the final decorated class can not be proxied.

One conclusion can be drawn: CGLib can proxy any class.

So why use the JDK's dynamic agent? Sure you would ask:

Based on years of actual project experience, it is known that CGLIB creates agents at a slower rate, but it runs very quickly after the agent is created, and the JDK dynamic agent is the opposite. If you continue to use CGLIB to create the agent at run time, the performance of the system will be greatly compromised, so it is recommended to use CGLIB to create the agent when the system is initialized, and put it into Spring ApplicationContext for later use.

III. Transaction Management through AOP

1.springaop.xml Configuration

    <!--Management of Things -    <Aop:configProxy-target-class= "true">//using gclib dynamic proxy mode        <Aop:pointcutID= "Studentgetmethod"expression= "Execution (* COM.SEEYON.SPRINGBEAN.AOP). *.*(..))" />//defining pointcuts        <Aop:advisorPointcut-ref= "Studentgetmethod"Advice-ref= "Txadvice" />    </Aop:config>    <Tx:adviceID= "Txadvice"Transaction-manager= "Txmanager">        <tx:attributes>            <Tx:methodname="*" />//To manage things in some way        </tx:attributes>    </Tx:advice>    <BeanID= "Txmanager"class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager"/>

Analyze Execution (* COM.SEEYON.SPRINGBEAN.AOP). *.*(..)) This tangent-point expression:

(1) The first * indicates that the return value of a method is arbitrary

(2) AOP: A child package that represents an AOP package and an AOP

(3) AOP: * represents all classes under the AOP package as well as the AOP sub-package

(4) AOP: *. * represents all methods of the AOP package and all classes under the AOP sub-package

(5) (..) Represents any of the method parameters

Here is a simple list of TransactionManager:org.springframework.jdbc.datasource.DataSourceTransactionManager and no attribute injection, please choose TRA according to your project Nsactionmanager.

java--Simple Spring AOP configuration and AOP things management, jdk/gclib dynamic proxy

Related Article

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.