java Spring AOP詳解及簡(jiǎn)單實(shí)例
一、什么是AOP
AOP(Aspect Oriented Programming)面向切面編程不同于OOP(Object Oriented Programming)面向?qū)ο缶幊蹋珹OP是將程序的運(yùn)行看成一個(gè)流程切面,其中可以在切面中的點(diǎn)嵌入程序。
舉個(gè)例子,有一個(gè)People類,也有一個(gè)Servant仆人類,在People吃飯之前,Servant會(huì)準(zhǔn)備飯,在People吃完飯之后,Servant會(huì)進(jìn)行打掃,這就是典型的面向切面編程.
其流程圖為:
二、Spring AOP實(shí)現(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("準(zhǔn)備食物"); } /** * 在吃飯之后 */ @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中進(jìn)行配置:
<?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中注冊(cè),否則不會(huì)生效,Spring會(huì)用這個(gè)bean進(jìn)行攔截--> <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(); }
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
java 與testng利用XML做數(shù)據(jù)源的數(shù)據(jù)驅(qū)動(dòng)示例詳解
這篇文章主要介紹了java 與testng利用XML做數(shù)據(jù)源的數(shù)據(jù)驅(qū)動(dòng)示例詳解的相關(guān)資料,需要的朋友可以參考下2017-01-01SpringBoot注冊(cè)FilterRegistrationBean相關(guān)情況講解
這篇文章主要介紹了SpringBoot注冊(cè)FilterRegistrationBean相關(guān)情況,借助FilterRegistrationBean來注冊(cè)filter,可以避免在web.xml種配置filter這種原始的寫法2023-02-02Springcloud RestTemplate服務(wù)調(diào)用代碼實(shí)例
這篇文章主要介紹了Springcloud RestTemplate服務(wù)調(diào)用代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08Spring SpringMVC,Spring整合MyBatis 事務(wù)配置的詳細(xì)流程
這篇文章給大家介紹SSM整合詳細(xì)流程步驟 Spring SpringMVC,Spring整合MyBatis 事務(wù)配置,本文通過實(shí)例圖文相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2020-10-10基于Failed?to?load?ApplicationContext異常的解決思路
這篇文章主要介紹了基于Failed?to?load?ApplicationContext異常的解決思路,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01