A-A+
使用注解实现SpringAop
SpringMVC启动的配置文件,扫描包时不要扫描Service,配置如下:
- <context:component-scan base-package="com.xnck">
- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
- </context:component-scan>
Spirng的配置文件,扫描包时不要扫描Controller,配置如下:
- <context:component-scan base-package="com.xnck">
- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
这样配置的原因是,因为springmvc的配置文件与spring的配置文件不是同时加载,如果不进行这样的设置,那么springmvc启动时就会将所有带@Service注解的类都扫描到容器中,等到加载spring配置文件的时候,因为容器内已经存在Service类,使得cglib将不对Service进行代理,从而导致AOP失效。
在Spring配置文件内,增加以下配置,启用@AspectJ风格的切面声明:
- <aop:aspectj-autoproxy />
增加一个基于@AspectJ风格的切面声明的类:
- import org.aspectj.lang.JoinPoint;
- import org.aspectj.lang.annotation.Aspect;
- import org.aspectj.lang.annotation.Before;
- import org.aspectj.lang.annotation.Pointcut;
- import org.springframework.stereotype.Component;
- import java.lang.annotation.Annotation;
- @Component
- @Aspect
- public class DataRuleInterceptor {
- @Pointcut("execution(public * com.xnck.service..*.*(..))")
- public void pointCut(){}
- @Before("pointCut()")
- public void getDataRule(JoinPoint joinPoint) throws Throwable{
- Annotation[] a = joinPoint.getTarget().getClass().getAnnotations();
- System.out.println("====================================");
- System.out.println(joinPoint.getSignature().getName());
- System.out.println("注解个数"+a.length);
- }
- }
这个类中的getDataRule方法将会在Service包内的所有public方法之前执行,然后再执行被调用的public方法。