JAVA 框架-Spring-AOP面向切面

AOP(Aspect Orient Programming),我們一般稱為面向方面(切面)編程,作為面向對象的一種補充,用于處理系統中分布于各個模塊的橫切關注點,比如事務管理、日志、緩存等等。AOP實現的關鍵在于AOP框架自動創建的AOP代理,AOP代理主要分為靜態代理和動態代理,靜態代理的代表為AspectJ;而動態代理則以Spring AOP為代表。

AOP配置示例:

需要的包:aspectjweaver-1.8.4.jar

數據訪問層:

package com.hanqi.dao;public class AppuserDao {public int deleteUser(int ids) {System.out.println(ids +"被刪除");yichang();//拋出一個異常return 1;}public void yichang() {throw new RuntimeException("出現錯誤!");}
}

?切面代理層:

package com.hanqi.util;public class LogginProxy {public void beforeMethod() {System.out.println("方法之前被調用!");}public void afterMethod() {System.out.println("方法之后被調用!");}public void returnMethod() {System.out.println("返回結果時被調用!");}public void throwMethod() {System.out.println("拋出異常時被調用!");}/*public void aroundMethod() {System.out.println("方法被調用");}*/
}

?spring.xml配置AOP

?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"><bean id="logginProxy" class="com.hanqi.util.LogginProxy"></bean><bean id="appuserdao" class="com.hanqi.dao.AppuserDao"></bean><aop:config><!-- 配置切點 --><aop:pointcutexpression="execution(* com.hanqi.dao.*.*(..))" id="aoppointcut" /><!--execution:執行,這句意為在執行com.hanqi.dao下的所有類時都會執行切面類--><!-- 指明切面類 --><aop:aspect ref="logginProxy"><aop:before method="beforeMethod"  pointcut-ref="aoppointcut"/><aop:after method="afterMethod" pointcut-ref="aoppointcut"/><aop:after-returning method="returnMethod" pointcut-ref="aoppointcut"/><aop:after-throwing method="throwMethod" pointcut-ref="aoppointcut"/>	</aop:aspect></aop:config>
</beans>

?JUnit Test測試:

package com.hanqi.util;import static org.junit.jupiter.api.Assertions.*;import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.hanqi.dao.AppuserDao;class JUnittest {private ClassPathXmlApplicationContext c;private AppuserDao appuserdao;@BeforeEachvoid setUp() throws Exception {c = new ClassPathXmlApplicationContext("spring.xml");appuserdao = c.getBean(AppuserDao.class);}@AfterEachvoid tearDown() throws Exception {c.close();}@Testvoid test() {appuserdao.deleteUser(55);}}

?打印結果:

使用注解配置AOP

spring.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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"><context:component-scan base-package="com.hanqi"></context:component-scan><!--配置掃描器-->
</beans>

數據訪問層:

package com.hanqi.dao;import org.springframework.stereotype.Repository;@Repository//加到spring容器中,id名默認為類名首字母小寫
public class AppuserDao {public int deleteUser(int ids) {System.out.println(ids +"被刪除");yichang();return 1;}public void yichang() {throw new RuntimeException("出現錯誤!");}
}

?AppuserService類:

package com.hanqi.service;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;import com.hanqi.dao.AppuserDao;
@Repository
public class AppuserService {@Autowired//從spring容器中將該類自動放到當前類中的成員變量中,默認的裝配類型時byType//@Qualifier("dao")該注解可將bean中id="dao"的類裝配到該成員變量中,用于區分當類型相同時;private AppuserDao appuserDao;public int deleteUser(int ids) {return appuserDao.deleteUser(ids);}
}

?代理類:

package com.hanqi.util;import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Repository;@Repository//加到spring容器中,id名為類名首字母小寫
@Aspect//聲明當前類為切面類
@EnableAspectJAutoProxy//自動代理
public class LogginProxy {@Before("execution(* com.hanqi.dao.*.*(..))")//聲明切點public void beforeMethod() {System.out.println("方法之前被調用!");}@After("execution(* com.hanqi.dao.*.*(..))")public void afterMethod() {System.out.println("方法之后被調用!");}@AfterReturning("execution(* com.hanqi.dao.*.*(..))")public void returnMethod() {System.out.println("返回結果時被調用!");}@AfterThrowing("execution(* com.hanqi.dao.*.*(..))")public void throwMethod() {System.out.println("拋出異常時被調用!");}/*public void aroundMethod() {System.out.println("方法被調用");}*/
}

?測試類:

package com.hanqi.util;import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.hanqi.dao.AppuserDao;
import com.hanqi.service.AppuserService;class JUnittest {private ClassPathXmlApplicationContext c;private AppuserDao appuserdao;private AppuserService appuserService;@BeforeEachvoid setUp() throws Exception {c = new ClassPathXmlApplicationContext("spring.xml");//appuserdao = c.getBean(AppuserDao.class);appuserService = c.getBean(AppuserService.class);}@AfterEachvoid tearDown() throws Exception {c.close();}@Testvoid test() {//appuserdao.deleteUser(55);appuserService.deleteUser(66);}}

?

轉載于:https://www.cnblogs.com/wyc1991/p/9245908.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/250016.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/250016.shtml
英文地址,請注明出處:http://en.pswp.cn/news/250016.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

互相關和卷積的關系

轉載于:https://www.cnblogs.com/seisjun/p/10134021.html

Thymeleaf3語法詳解

Thymeleaf是Spring boot推薦使用的模版引擎&#xff0c;除此之外常見的還有Freemarker和Jsp。Jsp應該是我們最早接觸的模版引擎。而Freemarker工作中也很常見&#xff08;Freemarker教程&#xff09;。今天我們從三個方面學習Thymeleaf的語法&#xff1a;有常見的TH屬性&#x…

【mysql】約束、外鍵約束、多對多關系

1、約束 DROP TABLE IF EXISTS emp;-- 員工表 CREATE TABLE emp (id INT PRIMARY KEY auto_increment, -- 員工id,主鍵且自增長ename VARCHAR(50) NOT NULL UNIQUE, -- 員工姓名,非空并且唯一joindate DATE NOT NULL, -- 入職日期,非空salary DOUBLE(7, 2) NULL, -- 工資,非空…

SSM+Netty項目結合思路

最近正忙于搬家&#xff0c;面試&#xff0c;整理團隊開發計劃等工作&#xff0c;所以沒有什么時間登陸個人公眾號&#xff0c;今天上線看到有粉絲想了解下Netty結合通用SSM框架的案例&#xff0c;由于公眾號時間限制&#xff0c;我不能和此粉絲單獨溝通&#xff0c;再此寫一篇…

[6]Windows內核情景分析 --APC

APC&#xff1a;異步過程調用。這是一種常見的技術。前面進程啟動的初始過程就是&#xff1a;主線程在內核構造好運行環境后&#xff0c;從KiThreadStartup開始運行&#xff0c;然后調用PspUserThreadStartup&#xff0c;在該線程的apc隊列中插入一個APC&#xff1a;LdrInitial…

THYMELEAF 如何用TH:IF做條件判斷

TestController 增加一個布爾值數據&#xff0c;并且放在model中便于視圖上獲取 package com.how2java.springboot.web; import java.util.ArrayList; import java.util.Date; import java.util.List;import org.springframework.stereotype.Controller; import org.springfr…

【mysql】多表查詢、左外連接、內連接、練習題

多表查詢 [外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-FBdzXkoQ-1659581225088)(C:\Users\L00589~1\AppData\Local\Temp\1659337934641.png)] 左外連接&右外連接 -- 查詢emp表所有數據和對應的部門信息 select * from emp left join dept o…

noi2018

day0 筆試沒啥問題&#xff0c;基本都是100 day1 時間有點緊&#xff0c;念了2h題目&#xff0c;能寫80848&#xff0c;第一題不會可持久化所以只能暴力。第二題感覺沒第三個好做。第三題sa亂搞&#xff0c;隨機串只hash長度小于20的。 最后幾分鐘才改過了所有小樣例&#xff0…

Python自建collections模塊

本篇將學習python的另一個內建模塊collections,更多內容請參考:Python學習指南 collections是Python內建的一個集合模塊&#xff0c;提供了許多有用的集合類。 namedtuple 我們知道tuple可以表示不變集合&#xff0c;例如&#xff0c;一個點的二維左邊就可以表示成&#xff1a;…

Thymeleaf th:include、th:replace使用

最近做到頁面數據展示分頁的功能&#xff0c;由于每個模塊都需要分頁&#xff0c;所以每個頁面都需要將分頁的頁碼選擇內容重復的寫N遍&#xff0c;如下所示&#xff1a; 重復的代碼帶來的就是CtrlC&#xff0c;CtrlV ,于是了解了一下thymeleaf的fragment加載語法以及th:includ…

(OS X) OpenCV架構x86_64的未定義符號:錯誤(OpenCV Undefined symbols for architecture x86_64: error)...

原地址&#xff1a;http://www.it1352.com/474798.html 錯誤提示如下&#xff1a; Undefined symbols for architecture x86_64:"cv::_InputArray::_InputArray(cv::Mat const&)", referenced from:_main in test-41a30e.o"cv::namedWindow(std::__1::basic…

【算法】大根堆

const swap (arr, i, j) > {const tmp arr[i];arr[i] arr[j];arr[j] tmp; } const heapInsert (arr , i) > { // 插入大根堆的插入算法while(arr[i] > arr[Math.floor((i - 1) / 2]) {swap(arr, i, Math.floor((i - 1) / 2);i Math.floor((i - 1) / 2; } } cons…

[CF1082E] Increasing Frequency

Description 給定一個長度為 \(n\) 的數列 \(a\) &#xff0c;你可以任意選擇一個區間 \([l,r]\) &#xff0c;并給區間每個數加上一個整數 \(k\) &#xff0c;求這樣一次操作之后數列中最多有多少個數等于 \(c\)。 \(n,c,a_i\leq 10^5\) Solution 假設當前選擇區間的右端點為 …

Thymeleaf select 使用 和多select 級聯選擇

1.使用select 并且回綁數據; 頁面&#xff1a; 狀態&#xff1a; <select name"status" th:field"*{status}" id"idstatus" class"input-select" th:value"*{status}"> <option value"">--請選擇-…

Switch語句的參數是什么類型的?

在Java5以前&#xff0c;switch(expr)中&#xff0c;exper只能是byte&#xff0c;short&#xff0c;char&#xff0c;int類型。 從Java5開始&#xff0c;java中引入了枚舉類型&#xff0c;即enum類型。 從Java7開始&#xff0c;exper還可以是String類型。 switch關鍵字對于多數…

【LOJ】#2184. 「SDOI2015」星際戰爭

題解 直接二分然后建圖跑網絡流看看是否合法即可 就是源點向每個激光武器連一條二分到的時間激光武器每秒攻擊值的邊 每個激光武器向能攻擊的裝甲連一條邊 每個裝甲向匯點連一條裝甲值的邊 代碼 #include <bits/stdc.h> #define fi first #define se second #define pii …

表達式符號

Thymeleaf對于變量的操作主要有$*#三種方式&#xff1a; 變量表達式&#xff1a; ${…}&#xff0c;是獲取容器上下文變量的值.選擇變量表達式&#xff1a; *{…}&#xff0c;獲取指定的對象中的變量值。如果是單獨的對象&#xff0c;則等價于${}。消息表達式&#xff1a; #{……

Java學習的快速入門:10行代碼學JQuery

生活在快速發展時代的我們&#xff0c;如果不提速可能稍不留神就被時代淘汰了。快節奏的時代成就了快餐&#xff0c;亦成就了速成教育。尤其是身處互聯網行業的我們&#xff0c;更新換代的速度更是迅速&#xff0c;快速掌握一門技術已經成為潮流趨勢。怎樣才能快速入門學習java…

項目管理

項目先后銜接的各個階段的全體被稱為項目管理流程。項目管理流程對于一個項目能否高效的執行起到事半功倍的效果。接下來我會利用36張的ppt&#xff08;當然了這里我只用部分圖片展示要不然就太多圖片了&#xff09;&#xff0c;介紹項目管理的整體流程。 1.項目管理的五大過程…

docker——三劍客之Docker Machine

Docker Machine是Docker官方三劍客項目之一&#xff0c;負責使用Docker的第一步&#xff0c;在多種平臺上快速安裝Docker環境。它支持多種平臺&#xff0c;讓用戶在很短時間內搭建一套Docker主機集群。Machine項目是Docker官方的開源項目&#xff0c;負責實現對Docker主機本身進…