注意添加:
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
两个jar包
方法调用拦截实现
package com.studio.advice; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.stereotype.Component; @Component public class MyAdvice implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { try{ System.out.println("interceptor-Befor:"); Object object= invocation.proceed(); System.out.println("interceptor-End:"); return object; }catch(Exception ex){ System.out.println("interceptor-ex:" + ex.getMessage()); throw ex; } } }
beens.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?> <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" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> <context:component-scan base-package="com.studio.*"/> <aop:config> <aop:pointcut id="mypointcut" expression="execution(* com..service..*(..))"/> <aop:advisor advice-ref="myAdvice" pointcut-ref="mypointcut" order="1" /> <aop:advisor advice-ref="myAdvice2" pointcut="execution(* com..service..*(..))" order="2" /> </aop:config> </beans>
说明
pointcut的execution中“*”表示一个单词(字母组成中间没空格)而“..”表示0或任意多个
定义注解:
package com.studio; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CheckLogin { }
注解切入点表达式
<aop:config> <aop:pointcut id="mypointcut" expression="execution(* com..service..*(..))"/> <aop:advisor advice-ref="myAdvice" pointcut-ref="mypointcut" order="1" /> <aop:advisor advice-ref="myAdvice2" pointcut="@annotation(com.studio.CheckLogin) or @target(com.studio.CheckLogin)" order="2" /> </aop:config>
说明:
允许在列或方法上放置CheckUser 以实现拦截
代码在参考华为网盘"软件测试与任务/spring"
参考:
http://blog.csdn.net/topwqp/article/details/8696897
http://blog.sina.com.cn/s/blog_5198c7370100hw1p.html
http://liusg123.iteye.com/blog/941546
http://lavasoft.blog.51cto.com/62575/172292/ 切入点表达式