Spring 通過註解方式實現AOP切面程式設計

2021-07-10 03:09:07 字數 2780 閱讀 8720

spring 切面程式設計的目的是實現**的業務邏輯的解耦。切面程式設計用於諸如日誌記錄,事務處理,等非業務性的邏輯操作。目前spring的aop只能應用於方法層級上,無法在類、成員欄位等層級上操作。以下是srping的aop程式設計分為註解方式和xml配置方式。以下過程詳細說明了通過註解方式實現aop程式設計的過程。

/**

* 定義自定義管理員註解

* */

public @inte***ce roleadmin

/*宣告為元件,讓spring 自動管理*/

@component

/*宣告該類為切面bean*/

@aspect

public class requestinterceptor

/*定義前置advice,同時接受joinpoint切入點物件,可以沒有該引數

在環繞通知裡面proceedingjoinpoint引數是必須的,其他情況joinpoint 並不是必須的

/** * 在切面中獲取http請求 * @return */

如果配置proxy-target-class="true",則表示是cglib**。如下:

如果採用jdk**,則配置如下:

/*在需要切面的方法上定義joincut點*/

@roleadmin(descript="在這裡定義")

其中,除ret-type-pattern和name-pattern之外,其他都是可選的。上例中,execution(* com.spring.service.*.*(..))表示com.spring.service包下,返回值為任意型別;方法名任意;引數不作限制的所有方法。

aop獲取註解和target物件

/*定義前置advice*/

@before("execution(* cn.ysh.studio.spring.aop.service..*(..))&&@annotation(roleadmin)")

public void admincommon(joinpoint point, roleadmin roleadmin)    

}  }

在spring中,任何通知(advice)方法都可以將第乙個引數定義為org.aspectj.lang.joinpoint型別用以接受當前連線點物件。joinpoint介面提供了一系列有用的方法, 比如 getargs() (返回方法引數)、getthis() (返回**物件)、gettarget() (返回目標)、getsignature() (返回正在被通知的方法相關資訊)和 tostring() (列印出正在被通知的方法的有用資訊)。

1、如果要設定多個切點,則使用||進行拼接

@pointcut("execution(* aop.annotation.*.*(..))|| execution(*com.action.admin.*.*update*(..))")

2、環繞通知的方法中一定要有proceedingjoinpoint 引數,與filter中的dofilter方法類似)

@around("execution(* aop.annotation.*.*(..))")

public object doaround(proceedingjoinpoint pjp) throws

通過註解方式配置Spring實現Ioc

1.首先需要配置spring,支援註解 加上這三句話在beans中 配置xml命名空間 xmlns context spring context 4.1.xsd 提示一下 xsd檔案,是用來約束xml檔案的語法和格式 約束xml檔案,有兩種標準 dtd dtd schema xsd 2.初始化和裝配...

Spring之通過註解方式實現AOP

乙個簡單的通過註解方式實現aop 通過aop統計方法呼叫耗時 目錄結構 具體類如下 配置類 package com.infuq.springaop import org.springframework.context.annotation.componentscan import org.sprin...

通過註解方式配置Spring的IoC

1.背景介紹 到目前為止,採用ssh框架,環境已經配置好。2.通過註解的環境配置 1.新增命名空間 xmlns context 命名空間的特點就是ns namespace 結尾 xsd用來約束xml檔案的語法和格式。約束xml檔案格式有兩種標準 1.dtd dtd 2.schema xsd 預設的命...