您的位置:首页 > 编程语言 > Java开发

spring-aop-xml

2013-03-10 21:05 309 查看
1.还是建立前面的依赖注入的例子上。
2.导入aopalliance.jar aspectjrt.jar aspectjweaver.jar三个包
3.新建LogAspect .java,注意此时的方法已经没有annotation(废话)。所以需要在bean.xml做配置

package org.zttc.itat.spring.proxy;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;

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

public void logStart(JoinPoint jp) {
//得到执行的对象
System.out.println(jp.getTarget());
//得到执行的方法
System.out.println(jp.getSignature().getName());
Logger.info("加入日志");
}
public void logEnd(JoinPoint jp) {
Logger.info("方法调用结束加入日志");
}

public void logAround(ProceedingJoinPoint pjp) throws Throwable {
Logger.info("开始在Around中加入日志");
pjp.proceed();//执行程序
Logger.info("结束Around");
}

}

4.bean.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 打开Spring的Annotation支持 -->
<context:annotation-config/>
<!-- 设定Spring 去哪些包中找Annotation -->
<context:component-scan base-package="org.zttc.itat.spring"/>

<aop:config>
<!-- 定义切面 -->
<aop:aspect id="myLogAspect" ref="logAspect">
<!-- 在哪些位置加入相应的Aspect -->
<aop:pointcut id="logPointCut" expression="execution(* org.zttc.itat.spring.dao.*.add*(..))||
execution(* org.zttc.itat.spring.dao.*.delete*(..))||
execution(* org.zttc.itat.spring.dao.*.update*(..))"/>
<aop:before method="logStart" pointcut-ref="logPointCut"/>
<aop:after method="logEnd" pointcut-ref="logPointCut"/>
<aop:around method="logAround" pointcut-ref="logPointCut"/>
</aop:aspect>
</aop:config>

</beans>

一般的aop都用xml,不用annotion
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: