之前SpringMVC+Mybatis整合,现在加上AOP

之前SpringMvc和mybatis整合的例子:http://www.cnblogs.com/acehalo/p/3901809.html

Controller类增加方法,以便测试:

    @RequestMapping(value = "/aopTest")
    @ResponseBody
    public String aopTest(HttpServletRequest request) {

        for (int i = 0; i < 3; i++) {
            aopServiceTest.doService();
        }

        return "hi";
    }

新增service类AopServiceTest:

package com.hi.test.service;

import org.springframework.stereotype.Service;

@Service
public class AopServiceTest {
    
    public void doService(){
        System.out.println("do service");
    }

}

 

新增切面类:

package com.hi.test.aop;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;




@Aspect
public class AopTest {

    
    @Pointcut("execution(* com.hi.test.service.*.*(..))")
    public void aspect(){    }
    
    @Before("aspect()")  
    public void before(){  
        System.out.println("Before");  
    } 
    
    @After("aspect()") 
    public void after(){
        System.out.println("After");  
    }
}

调整之前的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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
       ">
   
    <!-- spring aop -->
    <aop:aspectj-autoproxy proxy-target-class="true"/>

  
    <bean id="aop" class="com.hi.test.aop.AopTest"/> 

</beans>

如果不在spring-aop.xml中加入AopTest这个切面类,切面就没有用,感觉是自动扫描的时候没有扫到这个类,具体原因求知道的解释一下,不胜感激。

访问 http://localhost:8080/Test/aopTest.do

出现:
Before
do service
After
Before
do service
After
Before
do service
After

说明aop有用......

posted @ 2014-08-11 21:39 oh~NO! 阅读(...) 评论(...) 编辑 收藏