Spring is based on the annotation @ AspectJ AOP, spring @ aspectjaop

Source: Internet
Author: User

Spring is based on the annotation @ AspectJ AOP, spring @ aspectjaop

In addition to configuring AOP in XML, Spring also supports annotation: Use the @ AspectJ style aspect declaration.

However, the @ AspectJ support needs to be enabled in XML in Annotation mode.<Aop: aspectj-autoproxy/>,An AnnotationAwareAspectJAutoProxyCreator class will be created in the Spring context, and it will automatically proxy some beans. The Bean methods must match the cut points defined in Bena using the @ Aspect annotation, the cut points are defined using the @ Pointcut annotation. Let's take a look at the example below (PS: none of my examples contain parameters ):

The declared entry point @ AspectJ is implemented using the @ Pointcut method under the org. aspectj. lang. annotation package (the method must be of the void type returned. @ Pointcut (value = "Pointcut expression", argNames = "Parameter Name List ")
Public void pointcutName (......) {}
Declaration notification

Pre-notification

Use the @ Before annotation declaration under the org. aspectj. lang. annotation package;
@ Before (value = "entry point expression or naming entry point", argNames = "parameter list parameter name ")

Post-return notification

Use the @ AfterReturning annotation declaration under the org. aspectj. lang. annotation package;
@ AfterReturning (
Value = "entry point expression or named entry point ",
Pointcut = "pointcut expressions or named pointcut ",
ArgNames = "parameter list parameter name ",
Returning = "Response Parameter Name ")

Post-final notification

Use the @ After annotation declaration under the org. aspectj. lang. annotation package;
@ After (
Value = "entry point expression or named entry point ",
ArgNames = "parameter list parameter name ")

Post-exception notificationUse the @ AfterThrowing annotation declaration under the org. aspectj. lang. annotation package
@ AfterThrowing (
Value = "entry point expression or named entry point ",
Pointcut = "pointcut expressions or named pointcut ",
ArgNames = "parameter list parameter name ",
Throwing = "exception parameter name ")

package cn.com.ztz.spring.service;    public interface ShowService {      public void show();  } 

Package cn.com. ztz. spring. service; public class ShowServiceImpl implements ShowService {@ Override public void show () {showBefore (); // showError (); // exception test (post-exception notification) showEnd ();} public void showBefore () {System. out. println ("showBefore ==============");} public void showError () {System. out. println ("showError =============="); throw new RuntimeException ();} public void showEnd () {System. out. println ("showEnd ==================== ");}}

Package cn.com. ztz. spring. service; import org. aspectj. lang. annotation. afterReturning; import org. aspectj. lang. annotation. afterThrowing; import org. aspectj. lang. annotation. aspect; import org. aspectj. lang. annotation. before; import org. aspectj. lang. annotation. pointcut; @ Aspectpublic class AudienceAspect {// defines the cut point @ Pointcut ("execution (* cn.com. ztz. spring. service. showServiceImpl. show (..)) ") public void performance () {// the content of this method is not important. The method itself is only an identifier, @ Pointcut annotation attachment} // pre-notification @ Before ("performance ()") public void taskSeats () {System. out. println ("pending program start =");} // post notification @ After ("performance ()") public void applaud () {System. out. println ("applaud ==========");} // post exception notification @ AfterThrowing ("performance ()") public void demandRefund () {System. out. println ("refund departure ==== ");}}
<! -- Enable @ AspectJ support --> <aop: aspectj-autoproxy/> <bean id = "show" class = "cn.com. ztz. spring. service. showServiceImpl "/> <bean id =" audienceAspect "class =" cn.com. ztz. spring. service. audienceAspect "/>
public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");            ShowService hs = ctx.getBean("show", ShowService.class);            System.out.println("======================================");          hs.show();         System.out.println("======================================"); }

Run the test method console output:

==============================================
Waiting for program start =
ShowBefore ================
ShowEnd ======================
Applaud ==========
==============================================

Annotation surround notification

Like Spring's XML-based AOP, the use of @ AspectJ annotations not only limits and defines the pre-and post-notification types. We can also create a surround notification, which requires @ Around.

@ Around (
Value = "entry point expression or named entry point ",
ArgNames = "parameter list parameter name ")

public interface ShowService {      public void show(String param);  }
@Override      public void show(String param) {    System.out.println("around==========="+param);     } 
@ Aspectpublic class AudienceAspect {// defines the cut point @ Pointcut ("execution (* cn.com. ztz. spring. service. showServiceImpl. show (..)) ") public void performance () {// the content of this method is not important. the method itself is only an identifier for @ Pointcut annotation attachment} @ Around (" performance ()") public Object aroundAdvice (ProceedingJoinPoint pjp) throws Throwable {System. out. println ("around before advice =========="); Object retVal = pjp. proceed (new Object [] {"around"}); System. out. println ("around after advice ============"); return retVal ;}}
Run the test method console output:

==============================================
Around before advice ==============
Around = around
Around after advice ==============
==============================================

Introduction@ DeclareParents declaration in the org. AspectJ. lang. annotation package

@ DeclareParents (
Value = "AspectJ syntax type expression ",
DefaultImpl = "Default implementation class of the introduced interface ")
 

package cn.com.ztz.spring.service;public interface DeclareService {      public void declare();  }
package cn.com.ztz.spring.service;public class DeclareServiceImpl implements DeclareService {      @Override      public void declare() {          System.out.println("declare=====================");      }  } 
package cn.com.ztz.spring.service;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.DeclareParents;@Aspectpublic class AudienceAspect {@DeclareParents(value="cn.com.ztz.spring.service.ShowServiceImpl+",defaultImpl=cn.com.ztz.spring.service.DeclareServiceImpl.class)private DeclareService declareService;}

public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");    DeclareService hs = ctx.getBean("show", DeclareService.class);            System.out.println("======================================");          hs.declare();         System.out.println("======================================"); }

Output result of Running Test method:

==============================================
Declare ==================================
==============================================

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.