In this tutorial, we show you how to integrate AspectJ annotation with Spring AOP framework. In simple, Spring AOP + AspectJ allow you to intercept method easily.

Common AspectJ annotations :

  1. @Before – Run before the method execution
  2. @After – Run after the method returned a result
  3. @AfterReturning – Run after the method returned a result, intercept the returned result as well.
  4. @AfterThrowing – Run after the method throws an exception
  5. @Around – Run around the method execution, combine all three advices above.
Note
For Spring AOP without AspectJ support, read this build-in Spring AOP examples.

1. Directory Structure

See directory structure of this example.

2. Project Dependencies

To enable AspectJ, you need aspectjrt.jaraspectjweaver.jar and spring-aop.jar. See following Maven pom.xml file.

AspectJ supported since Spring 2.0
This example is using Spring 3, but the AspectJ features are supported since Spring 2.0.

File : pom.xml

<project ...>

    <properties>
<spring.version>3.0.5.RELEASE</spring.version>
</properties> <dependencies> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency> <!-- Spring AOP + AspectJ -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency> <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency> </dependencies>
</project>

3. Spring Beans

Normal bean, with few methods, later intercept it via AspectJ annotation.

package com.mkyong.customer.bo;

public interface CustomerBo {

    void addCustomer();

    String addCustomerReturnValue();

    void addCustomerThrowException() throws Exception;

    void addCustomerAround(String name);
} package com.mkyong.customer.bo.impl; import com.mkyong.customer.bo.CustomerBo; public class CustomerBoImpl implements CustomerBo { public void addCustomer(){
System.out.println("addCustomer() is running ");
} public String addCustomerReturnValue(){
System.out.println("addCustomerReturnValue() is running ");
return "abc";
} public void addCustomerThrowException() throws Exception {
System.out.println("addCustomerThrowException() is running ");
throw new Exception("Generic Error");
} public void addCustomerAround(String name){
System.out.println("addCustomerAround() is running, args : " + name);
}
}

4. Enable AspectJ

In Spring configuration file, put “<aop:aspectj-autoproxy />“, and define your Aspect (interceptor) and normal bean.

File : Spring-Customer.xml

<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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <aop:aspectj-autoproxy /> <bean id="customerBo" class="com.mkyong.customer.bo.impl.CustomerBoImpl" /> <!-- Aspect -->
<bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" /> </beans>

4. AspectJ @Before

In below example, the logBefore() method will be executed before the execution of customerBo interface, addCustomer()method.

Note
AspectJ “pointcuts” is used to declare which method is going to intercept, and you should refer to this Spring AOP pointcuts guide for full list of supported pointcuts expressions.

File : LoggingAspect.java

package com.mkyong.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before; @Aspect
public class LoggingAspect { @Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
public void logBefore(JoinPoint joinPoint) { System.out.println("logBefore() is running!");
System.out.println("hijacked : " + joinPoint.getSignature().getName());
System.out.println("******");
} }

Run it

	CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
customer.addCustomer();

Output

logBefore() is running!
hijacked : addCustomer
******
addCustomer() is running

5. AspectJ @After

In below example, the logAfter() method will be executed after the execution of customerBo interface, addCustomer()method.

File : LoggingAspect.java

 

package com.mkyong.aspect;
 
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;
 
@Aspect
public class LoggingAspect {
 
@After("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
public void logAfter(JoinPoint joinPoint) {
 
System.out.println("logAfter() is running!");
System.out.println("hijacked : " + joinPoint.getSignature().getName());
System.out.println("******");
 
}
 
}

Run it

	CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
customer.addCustomer();

Output

addCustomer() is running
logAfter() is running!
hijacked : addCustomer
******

6. AspectJ @AfterReturning

In below example, the logAfterReturning() method will be executed after the execution of customerBo interface,addCustomerReturnValue() method. In addition, you can intercept the returned value with the “returning” attribute.

To intercept returned value, the value of the “returning” attribute (result) need to be same with the method parameter (result).

File : LoggingAspect.java

package com.mkyong.aspect;
 
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
 
@Aspect
public class LoggingAspect {
 
@AfterReturning(
pointcut = "execution(* com.mkyong.customer.bo.CustomerBo.addCustomerReturnValue(..))",
returning= "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
 
System.out.println("logAfterReturning() is running!");
System.out.println("hijacked : " + joinPoint.getSignature().getName());
System.out.println("Method returned value is : " + result);
System.out.println("******");
 
}
 
}

Run it

	CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
customer.addCustomerReturnValue();

Output

addCustomerReturnValue() is running
logAfterReturning() is running!
hijacked : addCustomerReturnValue
Method returned value is : abc
******

7. AspectJ @AfterReturning

In below example, the logAfterThrowing() method will be executed if the customerBo interface,addCustomerThrowException() method is throwing an exception.

File : LoggingAspect.java

package com.mkyong.aspect;
 
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;
 
@Aspect
public class LoggingAspect {
 
@AfterThrowing(
pointcut = "execution(* com.mkyong.customer.bo.CustomerBo.addCustomerThrowException(..))",
throwing= "error")
public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {
 
System.out.println("logAfterThrowing() is running!");
System.out.println("hijacked : " + joinPoint.getSignature().getName());
System.out.println("Exception : " + error);
System.out.println("******");
 
}
}

Run it

	CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
customer.addCustomerThrowException();

Output

addCustomerThrowException() is running
logAfterThrowing() is running!
hijacked : addCustomerThrowException
Exception : java.lang.Exception: Generic Error
******
Exception in thread "main" java.lang.Exception: Generic Error
//...

8. AspectJ @Around

In below example, the logAround() method will be executed before the customerBo interface, addCustomerAround()method, and you have to define the “joinPoint.proceed();” to control when should the interceptor return the control to the original addCustomerAround() method.

File : LoggingAspect.java

package com.mkyong.aspect;
 
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
 
@Aspect
public class LoggingAspect {
 
@Around("execution(* com.mkyong.customer.bo.CustomerBo.addCustomerAround(..))")
public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
 
System.out.println("logAround() is running!");
System.out.println("hijacked method : " + joinPoint.getSignature().getName());
System.out.println("hijacked arguments : " + Arrays.toString(joinPoint.getArgs()));
 
System.out.println("Around before is running!");
joinPoint.proceed(); //continue on the intercepted method
System.out.println("Around after is running!");
 
System.out.println("******");
 
}
 
}

Run it

	CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
customer.addCustomerAround("mkyong");

Output

logAround() is running!
hijacked method : addCustomerAround
hijacked arguments : [mkyong]
Around before is running!
addCustomerAround() is running, args : mkyong
Around after is running!
******

Conclusion

It’s always recommended to apply the least power AsjectJ annotation. It’s rather long article about AspectJ in Spring. for further explanations and examples, please visit the reference links below.

Anti annotation or using JDK 1.4 ?
No worry, AspectJ supported XML configuration also, read this Spring AOP + AspectJ XML example.

Download Source Code

Download it – Spring3-AOP-AspectJ-Example.zip (8 KB)

原文地址:http://www.mkyong.com/spring3/spring-aop-aspectj-annotation-example/

Spring AOP + AspectJ Annotation Example---reference的更多相关文章

  1. Spring AOP + AspectJ annotation example

    In this tutorial, we show you how to integrate AspectJ annotation with Spring AOP framework. In simp ...

  2. Spring AOP @AspectJ 入门基础

    需要的类包: 1.一个简单的例子 Waiter接口: package com.yyq.annotation; public interface Waiter { void greetTo(String ...

  3. 关于 Spring AOP (AspectJ) 该知晓的一切

    关联文章: 关于Spring IOC (DI-依赖注入)你需要知道的一切 关于 Spring AOP (AspectJ) 你该知晓的一切 本篇是年后第一篇博文,由于博主用了不少时间在构思这篇博文,加上 ...

  4. Spring学习(十八)----- Spring AOP+AspectJ注解实例

    我们将向你展示如何将AspectJ注解集成到Spring AOP框架.在这个Spring AOP+ AspectJ 示例中,让您轻松实现拦截方法. 常见AspectJ的注解: @Before – 方法 ...

  5. 关于 Spring AOP (AspectJ) 你该知晓的一切

    版权声明:本文为CSDN博主「zejian_」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明.原文链接:https://blog.csdn.net/javazej ...

  6. 关于 Spring AOP (AspectJ) 你该知晓的一切 (转)

    出处:关于 Spring AOP (AspectJ) 你该知晓的一切

  7. Spring AOP AspectJ

    本文讲述使用AspectJ框架实现Spring AOP. 再重复一下Spring AOP中的三个概念, Advice:向程序内部注入的代码. Pointcut:注入Advice的位置,切入点,一般为某 ...

  8. spring AOP AspectJ 定义切面实现拦截

    总结记录一下AOP常用的应用场景及使用方式,如有错误,请留言. 1.  讲AOP之前,先来总结web项目的几种拦截方式    A:  过滤器 使用过滤器可以过滤URL请求,以及请求和响应的信息,但是过 ...

  9. Spring AOP AspectJ Pointcut Expressions With Examples--转

    原文地址:http://howtodoinjava.com/spring/spring-aop/writing-spring-aop-aspectj-pointcut-expressions-with ...

随机推荐

  1. Docker安装Gitlab

    一.Ubuntu16.4上Docker安装Gitlab 1.安装docker 参见:https://docs.docker.com/engine/installation/linux/ubuntuli ...

  2. Laravel之路——file缓存修改为redis缓存

    1.Session: 修改.evn文件: SESSION_DRIVER:redis (如果还不行的话,修改config/session.php的driver) 2.缓存修改为redis 注意:使用 L ...

  3. 转:实用 .htaccess 用法大全

    原文来自于:http://www.techug.com/htaccess-snippets 这里收集的是各种实用的 .htaccess 代码片段,你能想到的用法几乎全在这里. 免责声明: 虽然将这些代 ...

  4. 完全卸载mysql 停止服务、卸载相关程序、删除注册表

    本节主要介绍了完全卸载mysql的具体步骤包括停止服务.卸载相关程序.删除注册表等等   1. 停止服务MySQL 2. 卸载mysql相关的程序 3. 删除注册表(运行->regedit),m ...

  5. vijosP1902学姐的清晨问候

    题目:https://vijos.org/p/1902 题解:sb题...扫一遍每个字母出现的次数即可 代码: #include<cstdio> #include<cstdlib&g ...

  6. (转载)Mac和iOS开发资源汇总—更新于2013-07-19

    (转载)http://beyondvincent.com/2013/07/18/resources-for-mac-and-ios-developers/ 小引 本文主要汇集一些苹果开发的资源,会经常 ...

  7. C#操作Active Directory(AD)详解

    1. LDAP简介 LDAP(轻量级目录访问协议,Lightweight Directory Access Protocol)是实现提供被称为目录服务的信息服务.目录服务是一种特殊的数据库系统,其专门 ...

  8. javascipt取整数四舍五入

    1.丢弃小数部分,保留整数部分 parseInt(5/2) 2.向上取整,有小数就整数部分加1 Math.ceil(5/2) 3,四舍五入. Math.round(5/2) 4,向下取整 Math.f ...

  9. 这次GDC China 2015的总结与关卡设计教程的梳理

    去年关卡教程总结链接:听了GDC2014关于关卡设计的讲座的总结与自己的理解 24 号去了GDC china听了讲座,没有听unity没有听VR,听了一天关卡教程,和上次的关卡教程还是有区别的,这次的 ...

  10. js遍历数组和遍历对象的区别

    <script> //----------------for用来遍历数组对象-- var i,myArr = [1,2,3]; for (var i = 0; i < myArr.l ...