主要说两个问题:一、在Controller层实现aop。二、同类方法调用未触发切入。
因为现在网上资料比较多,我大概也是看到些帖子,自己根据遇到的一些问题做了一些总结。
一、在Controller层实现aop。
我的工程中有两个配置文件springmvc.xml和spring.xml,读者可能会有不同的命名,请对号入座。在Controller实现的配置必须写在springmvc.xml中,否则不起作用。
首先,加入aspect工具包,我使用的是maven。在pom.xml中加入:
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjtools</artifactId> <version>1.7.4</version> </dependency>
然后在springmvc.xml加入:
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation中加入:
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
文档中启用aop:
<aop:aspectj-autoproxy proxy-target-class="true"/>
这时候配置已经完成。
开始创建切入类,我使用的是注解方式,对类进行注解@Aspect
然后在类中创建方法,声明一个切入点,用@Pointcut,具体使用查看文档或者百度。
然后根据自己的业务需求加入@Before,@After,@AfterReturning,@AfterThrowing
@Aspect @Component public class SystemAspect { @Pointcut("within(com.aisino.rest.*) && " + "@annotation(org.springframework.web.bind.annotation.RequestMapping)") private void log() { System.out.println("======log"); } @Before("log()") public void before(JoinPoint joinPoint) { } @AfterReturning("log()") public void returning() { System.out.println("======returning"); } @AfterThrowing("log()") public void throwing() { System.out.println("======throwing"); } }
二、在Controller层中具体方法对应一个url分支,它们有一个HttpServletRequestrequest参数。
而在我的业务代码,我会使用一个父类继承的统一方法init读取request中的输入流。(我的参数是不是key-value形式,而是一段json串)
这里我要在进入方法前,进行权限判断,并且缓存一些日志所需数据。因此我必须要读取request中的输入流。
但是Servlet中的javax.servlet.ServletInputStream并没有对reset进行实现,也就是说只能读取一次,因此如果我在切入点的@Before方法中如果对request输入流进行读取,相应的业务方法就读不到数据了。因此问题陷入僵局,在此也欢迎各位能给出更好的解决方案。
因为每个Controller层的业务方法,第一步先运动init方法,输入流并且放入成员变量中,因此我打起了init的主意。
把init也作为一个切入点,但是发现对init的切入根本不起作用。而且对于具体的要进入的业务方法,可以正常切入。
不知道什么原因,因此init是本类(父类)的一个方法,所以调用不会触发切入方法。
搜索了很多资料,在一个帖子中得到启发。
使用AopContext.currentProxy(),然后强制转换一下,再调用init方法,就能触发切入了,具体为什么,大家可以根据方法搜索一下。
r = ((BaseController)AopContext.currentProxy()).init(request);
BaseController为我所有Controller继承的一个父类,实现了init方法。
完毕!
参考文献:http://www.thinksaas.cn/group/topic/350141/