1. 程式人生 > >Spring純POJO切面實現AOP

Spring純POJO切面實現AOP

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所切的服務的包名,即,我們的業務部分
包名後面的”..“  表示當前包及子包
第二個”*“  表示類名,*即所有類。此處可以自定義,下文有舉例
.*(..)  表示任何方法名,括號表示引數,兩個點表示任何引數型別