java Spring AOP詳解及簡單實例
一、什么是AOP
AOP(Aspect Oriented Programming)面向切面編程不同于OOP(Object Oriented Programming)面向?qū)ο缶幊?,AOP是將程序的運行看成一個流程切面,其中可以在切面中的點嵌入程序。
舉個例子,有一個People類,也有一個Servant仆人類,在People吃飯之前,Servant會準備飯,在People吃完飯之后,Servant會進行打掃,這就是典型的面向切面編程.
其流程圖為:

二、Spring AOP實現(xiàn):
1、People類:
public class People {
public void eat() {
System.out.println(“happyheng開始吃飯啦");
}
public void play(){
}
}
Servant類:
@Aspect
public class Servant {
/**
* 在吃飯之前
*/
@Before("execution(** com.happyheng.entity.People.eat(..))")
public void prepareFood(){
System.out.println("準備食物");
}
/**
* 在吃飯之后
*/
@After("execution(** com.happyheng.entity.People.eat(..))")
public void clean(){
System.out.println("打掃");
}
}
其中的 @Before是指執(zhí)行前,@After是指執(zhí)行方法后獲取方法拋出異常后,@AfterReturning是指在執(zhí)行方法后調(diào)用,@AfterThrowing是指方法拋出異常后調(diào)用。
2、在applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" xmlns:context="http://www.springframework.org/schema/context"> <context:component-scan base-package="com.happyheng" /> <aop:aspectj-autoproxy /> <!--注意Aspect的bean必須在Spring中注冊,否則不會生效,Spring會用這個bean進行攔截--> <bean class="com.happyheng.aop.Servant"></bean> <bean id="happyheng" class="com.happyheng.entity.People"></bean> </beans>
3、在main中使用:
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(APPLICATION_XML);
People happyheng = (People)ctx.getBean("happyheng");
happyheng.eat();
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Java編程實現(xiàn)提取文章中關(guān)鍵字的方法
這篇文章主要介紹了Java編程實現(xiàn)提取文章中關(guān)鍵字的方法,較為詳細的分析了Java提取文章關(guān)鍵字的原理與具體實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-11-11
JAVA中ListIterator和Iterator詳解與辨析(推薦)
這篇文章主要介紹了JAVA中ListIterator和Iterator詳解與辨析,需要的朋友可以參考下2017-04-04
Java簡單使用EasyExcel操作讀寫excel的步驟與要點
相信現(xiàn)在很多搞后端的同學大部分做的都是后臺管理系統(tǒng),那么管理系統(tǒng)就肯定免不了Excel的導出導入功能,下面這篇文章主要給大家介紹了關(guān)于Java簡單使用EasyExcel操作讀寫excel的步驟與要點,需要的朋友可以參考下2022-09-09
Java spring boot 實現(xiàn)支付寶支付功能的示例代碼
這篇文章主要介紹了Java spring boot 實現(xiàn)支付寶支付功能,本文通過實例代碼圖文相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06
Maven基礎(chǔ):錯誤對應:was cached in the local&nbs
這篇文章主要介紹了Maven基礎(chǔ):錯誤對應:was cached in the local repository的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-03-03
基于synchronized修飾靜態(tài)和非靜態(tài)方法
這篇文章主要介紹了基于synchronized修飾靜態(tài)和非靜態(tài)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-04-04

