A-A+

使用注解实现SpringAop

2016年01月05日 技术 暂无评论 阅读 3,356 次

SpringMVC启动的配置文件,扫描包时不要扫描Service,配置如下:

  1. <context:component-scan base-package="com.xnck">
  2.     <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
  3. </context:component-scan>

Spirng的配置文件,扫描包时不要扫描Controller,配置如下:

  1. <context:component-scan base-package="com.xnck">
  2.     <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  3. </context:component-scan>

这样配置的原因是,因为springmvc的配置文件与spring的配置文件不是同时加载,如果不进行这样的设置,那么springmvc启动时就会将所有带@Service注解的类都扫描到容器中,等到加载spring配置文件的时候,因为容器内已经存在Service类,使得cglib将不对Service进行代理,从而导致AOP失效。

在Spring配置文件内,增加以下配置,启用@AspectJ风格的切面声明:

  1. <aop:aspectj-autoproxy />

增加一个基于@AspectJ风格的切面声明的类:

  1. import org.aspectj.lang.JoinPoint;
  2. import org.aspectj.lang.annotation.Aspect;
  3. import org.aspectj.lang.annotation.Before;
  4. import org.aspectj.lang.annotation.Pointcut;
  5. import org.springframework.stereotype.Component;
  6. import java.lang.annotation.Annotation;
  7. @Component
  8. @Aspect
  9. public class DataRuleInterceptor {
  10.     @Pointcut("execution(public * com.xnck.service..*.*(..))")
  11.     public void pointCut(){}
  12.     @Before("pointCut()")
  13.     public void getDataRule(JoinPoint joinPoint) throws Throwable{
  14.         Annotation[] a = joinPoint.getTarget().getClass().getAnnotations();
  15.         System.out.println("====================================");
  16.         System.out.println(joinPoint.getSignature().getName());
  17.         System.out.println("注解个数"+a.length);
  18.     }
  19. }

这个类中的getDataRule方法将会在Service包内的所有public方法之前执行,然后再执行被调用的public方法。

给我留言

Copyright © 字痕随行 保留所有权利.   Theme  Ality

用户登录

分享到: