1. 程式人生 > >spring面向切面編程示例(xml配置形式vs@註解形式)

spring面向切面編程示例(xml配置形式vs@註解形式)

org .com frame 當前 分享圖片 tro wired 示例 img

一、xml配置形式

1、在Spring配置文件中增加面向切面配置
當調用com.activemq.service.impl.ConsumerServiceImpl接口實現類的任意方法時執行切面類中的方法。

技術分享圖片

2、寫切面類

技術分享圖片

註意:
1)不能對web層(比如:com.activemq.action.ConsumerController)做代理插入操作,親測無效。
(之前認為對web層進行切面處理無效,其實不是,無效的原因在於切面配置所在的文件,如果是spring-mvc.xml(Springmvc的配置文件)中,就有效,如果在applicationContext.xml(Spring的配置文件)中,就無效。)
2)<aop:pointcut>如果位於<aop:aspect>元素中,則命名切點只能被當前<aop:aspect>內定義的元素訪問到。為了能被整個<aop:config>元素中定義的所有增強訪問,則必須在<aop:config>下定義切點。

二、@Aspect註解形式

1、配置

在spring配置文件applicationContext.xml中啟用@Aspect,並聲明通知類

<!-- 聲明通知類 -->
<bean id="aspectBean" class="icom.axx.action.AopAspect" />
<!-- 啟用spring對AspectJ註解的支持 -->
<aop:aspectj-autoproxy />

2、寫通知類

package icom.axx.action;

import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.beans.factory.annotation.Autowired; import icom.axx.dao.AopAspectDao; /** * 面向切面類 * 用於保存幹線巡檢手機端調用接口的信息。 * @author
wangxiangyu * */ @Aspect public class AopAspect { @Autowired AopAspectDao aopAspectDao; public static final String EDP = "execution(* icom.axx.service.impl.*..*(..))"; /** * 前置通知:目標分方法調用之前執行 */ @Before(EDP) public void doBefore(JoinPoint jp){ } /** * 最終通知: * 目標方法調用之後執行(無論目標方法是否出現異常均執行) */ @After(EDP) public void doAfter(JoinPoint jp){ //獲取類名 String className = jp.getTarget().getClass().getName(); //調用的方法名 String methodName = jp.getSignature().getName(); //調用方法的參數 Object[] argArr = jp.getArgs(); String arg = ""; if(null != argArr && argArr.length>0) { for(Object argObj : argArr) { arg += argObj.toString(); } } //若傳遞參數大於300字符,只截取前300個字符。 if(arg.length()>300) { arg = arg.substring(0, 300); } Map<String, String> param = new HashMap<String, String>(); param.put("className", className); param.put("methodName", methodName); param.put("param_list", arg); //插入tb_base_mobile_gxxj_record aopAspectDao.saveInvokeInfo(param); } }

spring面向切面編程示例(xml配置形式vs@註解形式)