Spring的AOP配置--XML文件配置

首先導入aop的包和相關依賴包

在配置文件中創建增強方法的bean,隨後配置aop的相關內容

   <bean id="userService" class="com.aop.service.UserServiceImpl"></bean>
   <bean id="logger" class="com.aop.logger.LoggerTest"></bean>
   <aop:config>
        <!--配置切入點表達式-->
	    <aop:pointcut expression="execution(* *..*.*(..))" id="log"></aop:pointcut>
			<!--配置切面-->
			<aop:aspect id="logAop" ref="logger">
                                <!--前置通知-->
				<aop:before method="beforePrintLog" pointcut-ref="log"></aop:before>
				<!--後置通知-->
				<aop:after-returning method="afterReturingPrintLog" pointcut-ref="log"></aop:after-returning>
				<!--異常通知-->
				<aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="log"></aop:after-throwing>
				<!--最終通知-->
				<aop:after method="afterPrintLog" pointcut-ref="log"></aop:after>
				
			</aop:aspect>
		</aop:config>

配置切入點表達式時,表達式一定要加execution()  全通配表達式* *..*.*(..)

下面的是相關類的代碼

//	前置通知
	public void beforePrintLog() {
		System.out.println("前置通知beforePrintLog執行了");
	}

//	後置通知
	public void afterReturingPrintLog() {
		System.out.println("後置通知afterReturingPrintLog執行了");
	}

//	異常通知
	public void afterThrowingPrintLog() {
		System.out.println("異常通知afterThrowingPrintLog執行了");
	}

//	最終通知
	public void afterPrintLog() {
		System.out.println("最終通知afterPrintLog執行了");
	}

 此處根據你是否要測試異常來選擇註釋掉 int = 1/0;

	@Override
	public void findAllUser() {
		int i = 1/0;
		System.out.println("執行了查詢操作");
	}

環繞通知比較特殊,不能像之前其他通知一樣配置,以下配置會導致切入點方法不執行

	public Object aroundPrintLog() {
		System.out.println("環繞通知aroundPrintLog執行了");
		return null;




<aop:around method="aroundPrintLog" pointcut-ref="log"></aop:around>

由動態代理可知,環繞通知就是invoke方法,但環繞通知裏沒有明確的切入點方法調用
      解決:使用Spring提供的ProceedingJoinPoint,該接口可以作爲環繞通知方法的參數使用
      該接口有一個方法proceed(),此方法等同於method.invoke(),就是明確調用切入點方法

	public Object aroundPrintLog(ProceedingJoinPoint pjp) {
		Object result = null;
		try {
			System.out.println("前置通知執行了==========");
			
			result = pjp.proceed();
			
			System.out.println("後置通知執行了==========");
			
		} catch (Throwable e) {
			System.out.println("異常通知執行了==========");
			e.printStackTrace();
		}finally {
			System.out.println("最終通知執行了==========");
		}
		return result;
	}

 

此文章爲我個人的學習筆記總結,自用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章