代码改变世界

Spring AOP 一个简单的示例程序

2013-02-28 15:26  hduhans  阅读(192)  评论(0)    收藏  举报

1.①在配置xml文件中新增aop的标签元定义,

xmlns:aop="http://www.springframework.org/schema/aop"
<!--xsi:schemaLocation中新增-->
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

  ②新增aspectj的标签

<aop:aspectj-autoproxy/>   <!--用aspectj实现自动代理-->

  ③导入aspectj实现jar包 aspectjrt.jaraspectweave.jar

2.在切面点方法及类中说明增加切面说明,如

package com.bjsxt.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogInterceptor {

    @Before("execution(public void com.bjsxt.dao.impl.UserDAOImpl.save(com.bjsxt.model.User))")
    public void before(){
        System.out.println("before start!");
    }
}

3.完整实例程序点此下载

4.execution表达式

   ① execution(* com.xyz.service.AccountService.*(..))  代表com.xyz.service.AccountService类下的所有返回类型的所有方法

   ② execution(* com.xyz.service.*.*(..))  代表包com.xyz.service下的所有类中的所有返回类型的所有方法

   ③ execution(* com.xyz.service..*.*(..))  代表包com.xyz.service以及所有子包下的所有类中的所有返回类型的所有方法

 

5.当execution相同的表达式过多时,可以将其统一放置于一个地方,如:

@Pointcut("execution(public * com.bjsxt.dao..*.*(..))")
public void myMethod(){}
    
@Before("myMethod()")
public void before(){
    System.out.println("call before!");
}
    
@After("myMethod()")
public void after(){
    System.out.println("call after!");
}