Spring3基于注释驱动的AOP

51CTO正在组织十佳博客评选请

Spring3基于注释驱动的AOP

实在是郁闷刚刚编辑了一篇文章,由于字数的原因,没发布成功,好我就分开写吧,今天向大家介绍的是Spring基于注释驱动的AOP,其实估计这已经不是什么新技术了,但是我争取写的通俗易懂,大家从我这看一次就能明白,那就是我最高兴的了.

还是那样,今天我主要介绍如何配置,写出一个例子,然后大家按照例子一配就ok了.配置文件很简单,只需要在Spring配置文件中加入以下这句话就行了,下面这句话是让Spring启动自动AOP代理

 

 
 
  1. <!--启动spring的aop自动代理--> 
  2. <aop:aspectj-autoproxy/> 

然后再创建一个AOP类

 

 
 
  1. import org.aspectj.lang.JoinPoint;  
  2. import org.aspectj.lang.annotation.After;  
  3. import org.aspectj.lang.annotation.Aspect;  
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.stereotype.Service;  
  6.  
  7. import com.pdp.biz.dao.usermanage.UserDAO;  
  8.  
  9. /**  
  10.  * ClassName:DemoAop  
  11.  * Reason:   TODO ADD REASON  
  12.  *  
  13.  * @author   王涛  
  14.  * @version    
  15.  * @since    Ver 1.1  
  16.  * @Date     2010-11-24     上午10:25:18  
  17.  *  
  18.  */ 
  19. @Aspect 
  20. @Service 
  21. public class DemoAop {  
  22.     @Autowired 
  23.     public UserDAO userDao;  
  24.       
  25.     @After("execution(public * com.pdp.biz.service.usermanage.impl.UserManageServiceImpl.sayhi(..))")  
  26.     public void doAfter(JoinPoint jp) {  
  27.             System.out.println(userDao.findUsersCount(null));  
  28.             Object[] args = jp.getArgs();  
  29.             for(Object obj  : args){  
  30.                 System.out.println("参数值:"+obj);  
  31.             }  
  32.             System.out.println("后处理切入----------"+jp.getTarget().getClass().getName()+"----"+jp.getSignature().getName());  
  33.     }  

里面的注释分别是@Aspect用于告诉Spring这个是一个需要织入的类,

 

 
 
  1. @After("execution(public * com.pdp.biz.service.usermanage.impl.UserManageServiceImpl.sayhi(..))")  
  2.     public void doAfter(JoinPoint jp) { ... }

 

里面的doAfter方法上面有一行注释,指明这个方法将在UserManageServiceImpl.sayhi(..)方法运行结束之后来执行,参数JoinPoint主要携带了参数值和方法名什么的,到时候自己查查文档就ok了

 

org.aspectj.lang
Interface JoinPoint

All Known Subinterfaces:
ProceedingJoinPoint

public interface JoinPoint
 

 

Provides reflective access to both the state available at a join point and static information about it. This information is available from the body of advice using the special form thisJoinPoint. The primary use of this reflective information is for tracing and logging applications.

 aspect Logging {
     before(): within(com.bigboxco..*) && execution(public * *(..)) {
         System.err.println("entering: " + thisJoinPoint);
         System.err.println("  w/args: " + thisJoinPoint.getArgs());
         System.err.println("      at: " + thisJoinPoint.getSourceLocation());
     }
 }

Nested Class Summary
static interfaceJoinPoint.EnclosingStaticPart
           
static interfaceJoinPoint.StaticPart
          This helper object contains only the static information about a join point.
 
Field Summary
static java.lang.StringADVICE_EXECUTION
           
static java.lang.StringCONSTRUCTOR_CALL
           
static java.lang.StringCONSTRUCTOR_EXECUTION
           
static java.lang.StringEXCEPTION_HANDLER
           
static java.lang.StringFIELD_GET
           
static java.lang.StringFIELD_SET
           
static java.lang.StringINITIALIZATION
           
static java.lang.StringMETHOD_CALL
           
static java.lang.StringMETHOD_EXECUTION
          The legal return values from getKind()
static java.lang.StringPREINITIALIZATION
           
static java.lang.StringSTATICINITIALIZATION
           
static java.lang.StringSYNCHRONIZATION_LOCK
           
static java.lang.StringSYNCHRONIZATION_UNLOCK
           
 
Method Summary
 java.lang.Object[]getArgs()
          Returns the arguments at this join point.
 java.lang.StringgetKind()
          Returns a String representing the kind of join point.
 SignaturegetSignature()
          Returns the signature at the join point.
 SourceLocationgetSourceLocation()
          Returns the source location corresponding to the join point.
 JoinPoint.StaticPartgetStaticPart()
          Returns an object that encapsulates the static parts of this join point.
 java.lang.ObjectgetTarget()
           Returns the target object.
 java.lang.ObjectgetThis()
           Returns the currently executing object.
 java.lang.StringtoLongString()
          Returns an extended string representation of the join point.
 java.lang.StringtoShortString()
          Returns an abbreviated string representation of the join point.
 java.lang.StringtoString()
           

运行的时候直接运行就ok了.

 
 
  1. @Test    
  2. public void testgetUsers(){  
  3.       userManageService.sayhi("Hi 大家好~!");  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring AOPSpring框架中的一个重要模块,它提供了面向切面编程(AOP)的支持。AOP是一种编程思想,它可以在不改变原有代码的情况下,通过在程序运行时动态地将代码“织入”到现有代码中,从而实现对原有代码的增强。 Spring AOP提供了基于注解的AOP实现,使得开发者可以通过注解的方式来定义切面、切点和通知等相关内容,从而简化了AOP的使用。 下面是一个基于注解的AOP实现的例子: 1. 定义切面类 ```java @Aspect @Component public class LogAspect { @Pointcut("@annotation(Log)") public void logPointcut() {} @Before("logPointcut()") public void beforeLog(JoinPoint joinPoint) { // 前置通知 System.out.println("执行方法:" + joinPoint.getSignature().getName()); } @AfterReturning("logPointcut()") public void afterLog(JoinPoint joinPoint) { // 后置通知 System.out.println("方法执行完成:" + joinPoint.getSignature().getName()); } @AfterThrowing(pointcut = "logPointcut()", throwing = "ex") public void afterThrowingLog(JoinPoint joinPoint, Exception ex) { // 异常通知 System.out.println("方法执行异常:" + joinPoint.getSignature().getName() + ",异常信息:" + ex.getMessage()); } } ``` 2. 定义业务逻辑类 ```java @Service public class UserService { @Log public void addUser(User user) { // 添加用户 System.out.println("添加用户:" + user.getName()); } @Log public void deleteUser(String userId) { // 删除用户 System.out.println("删除用户:" + userId); throw new RuntimeException("删除用户异常"); } } ``` 3. 在配置文件中开启AOP ```xml <aop:aspectj-autoproxy/> <context:component-scan base-package="com.example"/> ``` 在这个例子中,我们定义了一个切面类LogAspect,其中通过@Aspect注解定义了一个切面,通过@Pointcut注解定义了一个切点,通过@Before、@AfterReturning和@AfterThrowing注解分别定义了前置通知、后置通知和异常通知。 在业务逻辑类中,我们通过@Log注解标注了需要增强的方法。 最后,在配置文件中,我们通过<aop:aspectj-autoproxy/>开启了AOP功能,并通过<context:component-scan>扫描了指定包下的所有组件。 这样,当我们调用UserService中的方法时,就会触发LogAspect中定义的通知,从而实现对原有代码的增强。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值