笔者花了一点时间进行了关于spring aop标签的使用,希望能帮助初学spring框架的童鞋们。
只列举了最重要的部分。供参考
1.定义切面类
package com.lm.aop.xml;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
public class XmlHandler {
//前置通知
public void before(JoinPoint point){
System.out.println(point.getSignature().getName()+"执行之前,before....");
}
//后置通知
public void after(JoinPoint point){
System.out.println(point.getSignature().getName()+"执行之前,after....");
}
//方法返回后通知
public void returnafter(JoinPoint point){
System.out.println(point.getSignature().getName()+"正常执行之后,returnafter....");
}
//环绕通知
public Object around(ProceedingJoinPoint pjp) throws Throwable{
System.out.println(pjp.getSignature().getName()+"执行之前,around....");
Object proceed = pjp.proceed(); //执行目标对象的方法
System.out.println(pjp.getSignature().getName()+"执行之后,around....");
return proceed;
}
//异常通知
public void throwingException(JoinPoint point,Exception ex){
System.out.println(point.getSignature().getName()+"发生异常"+ex.getMessage());
}
}
2.Spring Xml配置(Aop标签)
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?>
xmlns:xsi
=
"
http://www.w3.org/2001/XMLSchema-instance"
;
xmlns:context
=
"
http://www.springframework.org/schema/context"
;
<!--配置account对象 -->
<
bean
name
=
"account"
class
=
"com.lm.aop.bean.Account"
>
<
property
name
=
"id"
value
=
"1"
></
property
>
<
property
name
=
"name"
value
=
"LeeSin"
></
property
>
<
property
name
=
"balance"
value
=
"5000"
></
property
>
</
bean
>
<!--配置
dao
层 -->
<
bean
name
=
"dao"
class
=
"com.lm.aop.dao.AccountDaoImpl"
></
bean
>
<!-- 配置service -->
<
bean
name
=
"service"
class
=
"com.lm.aop.service.AccountServiceImpl"
>
<
property
name
=
"dao"
ref
=
"dao"
></
property
>
<
property
name
=
"fromAccount"
ref
=
"account"
></
property
>
</
bean
>
<!--配置切面类对象 -->
<
bean
name
=
"handler"
class
=
"com.lm.aop.xml.XmlHandler"
></
bean
>
<!-- aopConfig配置代理对象 -->
<
aop:config
>
<!-- execution(修饰符(可以不写) 参数类型(必须写可以用*代替) 包名+类名+方法名(可以用*代替(..) ..的意思是代表参数可有可无。 )) -->
<
aop:pointcut
expression
=
"execution(* com.briup.aop.service.*.*(..))"
id
=
"myPointCut"
/>
<
aop:aspect
id
=
"aspect"
ref
=
"handler"
>
<
aop:before
method
=
"before"
pointcut-ref
=
"myPointCut"
/>
<
aop:after
method
=
"after"
pointcut-ref
=
"myPointCut"
/>
<
aop:around
method
=
"around"
pointcut-ref
=
"myPointCut"
/>
</
aop:aspect
>
</
aop:config
>
</
beans
>