1.导包
aopalliance.jar
aspectjweaver.jar
2.编写Controller
package com.chen.web;
@Controller
@RequestMapping("/list")
public class MyController {
@RequestMapping("test.html")
public String test(HttpServletRequest req, HttpServletResponse res){
return "../NewFile";
}
}
3.创建横切处理类
package com.chen.aspect;
public class TestHelper {
public void printTime(){
System.out.println("current time :"+System.currentTimeMillis());
}
}
4.创建AOP配置文件spring-aop.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<bean id="myController" class="com.chen.web.MyController"/>
<bean id="timeHandler" class="com.chen.aspect.TestHelper"/>
<aop:config>
<aop:aspect id="time" ref="timeHandler">
<aop:pointcut expression="execution(* com.chen.web.MyController.test(..))" id="addAllMethod"/>
<aop:before method="printTime" pointcut-ref="addAllMethod"/>
<aop:after method="printTime" pointcut-ref="addAllMethod"/>
</aop:aspect>
</aop:config>
</beans>
5.部署tomcat,并测试
execution表达式解释
execution(* com.chen.aspect..*.*(..))
符号 | 含义 |
execution() | 表达式的主体; |
第一个”*“符号 | 表示返回值的类型任意; |
com.chen.aspect | AOP所切的服务的包名,即,我们的业务部分 |
包名后面的”..“ | 表示当前包及子包 |
第二个”*“ | 表示类名,*即所有类。此处可以自定义,下文有举例 |
.*(..) | 表示任何方法名,括号表示参数,两个点表示任何参数类型 |