步骤:
a)在beans.xml文件中加上对应的xsd文件 spring-aop.xsd
b)加上<aop:aspectj-autoproxy>,使用aspectj来完成aop
<!-- 使用AspectJ 中的 AOP注解 需要先加上下面这句 --> <aop:aspectj-autoproxy/> </beans>
c) 此时就可以解析对应的 Annotation
d) 建立我们的拦截类
e) 用 @Aspect 注解这个类
f) 建立处理方法
g) 用@Before 来注解方法
h) 写明白切入点(execution)
i) 让 spring 对我们的拦截器类进行管理
常见的Annotation
1.@Pointcut 切入点声明,以供其他方法使用
2.@Before 方法 执行之前织入
3.@AfterThrowing 方法抛出异常后织入
4.@After 类似异常的finally
5.@Around 环绕 类似 filter,如需继续往下执行,则需要像filter中执行FilterChain.doFilter(..)一样
执行ProceedingJoinPoint.proceed() 方可,
1 @Around("execution(* com.bjsxt.dao..*.*(..))") 2 public void before(ProceedingJoinPoint pjp) throws Throwable{ 3 System.out.println("method start"); 4 pjp.proceed();//类似FilterChain.doFilter(..)告诉jvm继续向下执行 5 }
拦截器类:
1 /*使用 Aspectj 的AOP 自动生成代理*/ 2 @Aspect 3 /*这个类也需要被加载到Spring容器中,不然怎么代理*/ 4 @Component 5 public class MethodInterceptor { 6 //@Before("execution(public void com.bjsxt.service.UserService.add(com.bjsxt.model.User))") 7 //不能直接针对UserService 进行织入,是因为,UserService没有实现接口,要导入 cglib 8 //在一个类没有实现接口时,如果要生成代理,需要使用 cglib.jar 来操作二进制码 来产生 代理的代码 9 10 //定义一个切点的集合 ,为这个集合起一个名字,为myMethod 11 //想使用这个切点的集合,只需要 以 myMethod 为value 即可 12 //public * com.bjsxt.service..*.add(..)) ==== com.bjsxt.service的任意子包下的任意类的add方法 13 @Pointcut("execution(public * com.bjsxt.service..*.add(..))") 14 public void myMethod(){}; 15 16 //一个类如果实现了 接口,会使用JDK自带的 Proxy 和 InvocationHandler,来帮你产生代理 17 @Before("myMethod()") 18 public void beforeMethod() { 19 System.out.println("before"); 20 } 21 22 /*在方法返回结果之后,织入*/ 23 @AfterReturning("myMethod()") 24 public void afterMethod() { 25 System.out.println("after"); 26 } 27 28 /*将指定方法around住,可以在这个方法前后织入业务,proceed() 执行此方法*/ 29 @Around("myMethod()") 30 public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable { 31 System.out.println("Before Around Method"); 32 pjp.proceed(); 33 System.out.println("After Around Method"); 34 } 35 }
测试类:
1 public class UserServiceTest { 2 @Test 3 public void test() throws Exception{ 4 5 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); 6 //注:因为UserService 没有实现接口,使用cglib 操作二进制码,生成代理对象,所以这里是直接使用 UserService 去接收, 7 //在 UserService 实现了接口的情况下,就需要是用那个接口去接收,因为 在 使用jdk的 Proxy生成代理对象时,返回的是实现了这个接口的代理类,而不是UserService 8 UserService service = (UserService) applicationContext.getBean("userService"); 9 10 service.add(new User()); 11 } 12 }
a) 加上对应的xsd文件spring-aop.xsd