Spring Detailed (vi)------AOP annotations

Source: Internet
Author: User
Tags throw exception

On a previous blog we explained how the AspectJ framework implements AOP, and then the specific implementation is configured through XML. The idea of XML is clear and easy to understand, but it is too cumbersome to write. This blog is an annotated way to configure AOP.

In order to make it easier for everyone to understand, the way to explain this is that we first give the XML configuration and then explain how to replace it with annotations.

PS: This blog source download link: Http://pan.baidu.com/s/1dFdBHZF Password: 3v4k

1. Implementing AOP in the form of XML

  ①, Interface UserService

Package Com.ys.aop;public interface UserService {//Add userpublic void AddUser ();//delete userpublic void DeleteUser ();}

  ②, Implementing Class Userserviceimpl

Package Com.ys.aop;public class Userserviceimpl implements userservice{@Overridepublic void AddUser () { System.out.println ("Add User");} @Overridepublic void DeleteUser () {System.out.println ("delete User");}}

  ③, Slice class, that is, notification class Myaspect

Package Com.ys.aop;import Org.aspectj.lang.joinpoint;public class Myaspect {/** * Joinpoint can get some basic information about the target method * @param JOINP oint */public void Mybefore (Joinpoint joinpoint) {System.out.println ("Pre-Notification:" + joinpoint.getsignature (). GetName ());} public void myafterreturning (Joinpoint joinpoint,object ret) {System.out.println ("Post notification:" + joinpoint.getsignature (). GetName () + ",--" + ret);} public void myafterthrowing (Joinpoint joinpoint,throwable e) {System.out.println ("Throw exception Notification:" + e.getmessage ());} public void Myafter () {System.out.println ("final Notice");}}

  ④, AOP configuration file Applicationcontext.xml

<?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:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xsi:schemalocation= "Http://www.springframework.org/schema /beans http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/sche MA/AOP http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/c Ontext http://www.springframework.org/schema/context/spring-context.xsd "><!--1, create target class--><bean id=" us Erservice "class=" Com.ys.aop.UserServiceImpl "></bean> <!--2, create slice Class (notification)--<bean id=" Myaspect " class= "Com.ys.aop.MyAspect" ></bean><!--3, AOP programming 3.1 importing Namespaces 3.2 using <aop:config> When you configure proxy-target-class= "true" declaration, use Cglib proxy if not declared, Spring automatically chooses Cglib proxyor JDK dynamic proxy <aop:pointcut> pointcut, get specific methods from target objects <aop:advisor> special facets, only one notification and one pointcut ADVICE-REF notification reference Pointcut-ref Pointcut reference 3.3 pointcut expression Execution (* com.ys.aop.*.* (..)) Select method return value any package class name arbitrary method name arbitrary parameter arbitrary--><aop:config><aop:aspect ref= "Myaspect" ><!--pointcut Expression--><aop:pointcut expression= "Execution (* com.ys.aop.*.* (..))" id= "Mypointcut"/><!--3.1 pre-notification &LT;AOP: Before method= "" pointcut= "" pointcut-ref= ""/>method: Notification, and Method name Pointcut: pointcut expression, this expression can only be used by the current notification. Pointcut-ref: pointcut Reference, you can share pointcuts with other notifications. Notification method format: public void Mybefore (Joinpoint joinpoint) {parameter 1:org.aspectj.lang.joinpoint is used to describe the connection point (target method), get the target method name, etc.-->< Aop:before method= "Mybefore" pointcut-ref= "Mypointcut"/><!--3.2 post notification, execute after target method, get return value <aop:after-returning Method= "" pointcut-ref= "" returning= ""/>returning notification method The name of the second parameter notifies the method format: public void myafterreturning (joinpoint Joinpoint,object ret) {parameter 1: Connection point description Parameter 2: Type Object, parameter name returning= "ret" Configuration--><aop:after-returning method= " Myafterreturning "Pointcut-ref= "Mypointcut" returning= "ret"/><!--3.3 Final Notice--><aop:after method= "Myafter" pointcut-ref= "MyPointCut"/ ></aop:aspect></aop:config></beans>

  ⑤, testing

@Testpublic void Testaop () {ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml") ; UserService Useservice = (userservice) context.getbean ("UserService"); Useservice.adduser (); UseService.deleteUser () ;}

  ⑥, console print results

  

The above example is simple, that is, in the UserService AddUser () method and the DeleteUser () method to increase the pre-notification and post-notification, which is very well understood in the actual operation. For example, if this is dealing with a database, then we must start the transaction in front of the AddUser () or deleteuser () and commit the transaction after the operation is complete. Here we will use annotations to configure the way.

2. Annotations to implement AOP

  ①, import the appropriate jar packages, and import the appropriate namespaces in the Applicationcontext.xml file. This is available in the source download link above

  

<?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:context= "Http://www.springframework.org/schema /context "       xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "       xsi:schemalocation="/http/ Www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/spring-beans.xsd          http ://www.springframework.org/schema/aop           http://www.springframework.org/schema/aop/spring-aop.xsd/          http Www.springframework.org/schema/context           http://www.springframework.org/schema/context/spring-context.xsd " ></beans>

  

②, annotation configuration bean

XML configuration:

<!--1, create target class--><bean id= "UserService" class= "Com.ys.aop.UserServiceImpl" ></bean>   <!--2, Create a slice class (notification)--  <bean id= "Myaspect" class= "Com.ys.aop.MyAspect" ></bean>

Annotation configuration:

Target class:

  

Slice class:

  

③, configuring scan annotation Recognition

This is what we've said before, how does Spring recognize annotations on these classes, as configured above? We have to tell him.

Add the following configuration in the Applicationcontext.xml file:

<!--configuration scan annotation class Base-package: Represents the package name that contains the annotation class. If you scan multiple packages, the following code writes multiple lines, changing the contents of the Base-package! --><context:component-scan base-package= "COM.YS.AOP" ></context:component-scan>

  

  ④, annotations Configuring AOP

  One, we have configured the following with XML:

  

This is telling Spring which is the slice class. Below we use annotations to configure

We add @Aspect annotations on the slice class as follows:

  

How do we let Spring know about the AOP annotations we have configured? It is not enough to have the previous class annotation scan, where we need to configure an additional AOP annotation recognition.

We add the following configuration to the Applicationcontext.xml file:

<!--2 to determine the validity of AOP annotations  --><aop:aspectj-autoproxy></aop:aspectj-autoproxy>

  

  Third, note configuration pre-notification

Let's look at the XML configuration pre-notification as follows:

<!--pointcut expression--><aop:pointcut expression= "Execution (* com.ys.aop.*.* (..))" id= "Mypointcut"/><!--3.1 Pre-notification <aop:before method= "" pointcut= "" pointcut-ref= ""/>method: Notification, and Method name Pointcut: pointcut expression, this expression can only be used by the current notification. Pointcut-ref: pointcut Reference, you can share pointcuts with other notifications. Notification method format: public void Mybefore (Joinpoint joinpoint) {parameter 1:org.aspectj.lang.joinpoint  used to describe the connection point (target method), get the target method name, etc.-- <aop:before method= "Mybefore" pointcut-ref= "Mypointcut"/>

Then the annotations are in the following way:

  

  Iv. annotation configuration post-placement notification

XML configuration post-notification:

<!--3.2 Post notification  , after the target method is executed, gets the return value <aop:after-returning method= "" pointcut-ref= "" returning= ""/>returning Notification method Name of the second parameter notification method format: public void myafterreturning (Joinpoint joinpoint,object ret) {parameter 1: Connection point description Parameter 2: Type Object, parameter name returning = "ret" configuration--><aop:after-returning method= "myafterreturning" pointcut-ref= "Mypointcut" returning= "ret"/>

Note that the post notification has a returning= "ret" configuration, which is used to obtain the return value of the target method.

The annotations are configured as follows:

  

  V. Testing

@Testpublic void Testaopannotation () {ApplicationContext context = new Classpathxmlapplicationcontext (" Applicationcontext_annotation.xml "); UserService Useservice = (userservice) context.getbean ("UserService"); Useservice.adduser (); UseService.deleteUser () ;}

  Six, console printing results

  

3. Improvement of annotations

We can look at the annotation configuration for the pre-notification and post-notification:

  

Watch out for the red box, which is obviously repetitive, and if we have multiple notification methods, we have to write the annotations in each method name, and if the package names are complex enough, it's easy to write them wrong. So what do we do?

The solution is to declare a public entry point:

①, a new Pointcut method Mypointcut () is added to the slice class Myaspect.java, and @Pointcut annotations are added to this method

  

②, then the pre-notification and post-notification, we can make the following rewrite configuration:

  

4. Summary

Above we only carry out the pre-notification and post-notification of the explanation, as well as such as the final notice, surround notification, throw exception notification, configuration is similar, here is not one by one explanation. Then let's take a look at the notes for these notifications:

@Aspect declare slices, and modify the slice class to get notifications.

Notice

@Before front-facing

@AfterReturning Rear-facing

@Around Surround

@AfterThrowing throws an exception

@After eventually

Pointcut

@PointCut, the modifier method private void xxx () {} Obtains a pointcut reference through the method name

Spring Detailed (vi)------AOP annotations

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.