Spring AOP入门 (三)基于Annotation

这里讲如何使用Annotation来实现Spring的AOP功能。
通过Annotation来实现Spring的AOP功能,要导入几个包:
aspectjrt.jar
aopalliance.jar
aspectjweaver.jar


[b]1. 首先在beans.xml中加入aop的schema[/b]

 xmlns:aop="http://www.springframework.org/schema/aop"

http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd



[b]2. 打开基于Annotation的AOP功能。[/b]


<!-- Enables the use of the @AspectJ style of Spring AOP. -->	
<aop:aspectj-autoproxy/>


[b]3. 定义一个切面类 - Declaring an aspect class[/b]
package com.lj.proxy;

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

import com.lj.log.Logger;


@Component("logAspect") //让这个切面类被Spring所管理
@Aspect //声明这个类是一个切面类
public class LogAspect {


/**
* 这就是通知 advice
* execution(xx)就是pointcut表达式
* 第一个*表示任意返回值,
* 第二个*表示该包里面所有的类,
* add*表示所有以add开头的方法
* (..)表示里面是任意的参数
* 通过||可以放入多个pointcut
*/
@Before(value = "execution(* com.lj.dao.*.add*(..))||"+
"execution(* com.lj.dao.*.update*(..))||"+
"execution(* com.lj.dao.*.list*(..))")
public void logStart(){
Logger.info("加入日志");
}
}


此时我们便不需要去修改service层的注入对象了。

@Service("userService")
public class UserService implements IUserService {

@Resource(name="userDao") //这里不需要用userDynamicDao,UserDynamicDao类也不用写了。
private IUserDao userDao;



但是这里在LogAsprct中并没有获取方法名称,如何获取方法名称呢?
[b]4. 通过JointPoint获取方法[/b]

	public void logStart(JoinPoint jp){

//返回类对象
System.out.println(jp.getTarget());
//Signature.getName()返回方法名称
System.out.println(jp.getSignature().getName());
Logger.info("加入日志");
}

getTarget() ->返回调用的类对象。
Singature.getName() ->返回调用的方法。


5. 设置@After, @Around


//After表示在方法被调用结束之后才开始执行
@After(value = "execution(* com.lj.dao.*.list*(..))")
public void endStart(JoinPoint jp) {
Logger.info("方法调用结束");
// 返回类对象


}


@Around(value = "execution(* com.lj.dao.*.list*(..))")
public void logAround(ProceedingJoinPoint proceedingJoinPoint){
Logger.info("开始在Around中加入日志");
try {
proceedingJoinPoint.proceed();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //执行程序
Logger.info("Around执行结束");

}


最终调用UserDao的list方法,执行结果如下:

[img]http://dl2.iteye.com/upload/attachment/0092/0275/49c56d97-83e6-383b-95f5-83af9e38521d.jpg[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值