AOP的概念與簡單使用
一、什麼是AOP
AOP(Aspect Oriented Programming)面向切面程式設計不同於OOP(Object Oriented Programming)面向物件程式設計,AOP是將程式的執行看成一個流程切面,其中可以在切面中的點嵌入程式。
舉個例子,有一個People類,也有一個Servant僕人類,在People吃飯之前,Servant會準備飯,在People吃完飯之後,Servant會進行打掃,這就是典型的面向切面程式設計.
其流程圖為:
二、Spring AOP實現:
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是指執行前,@After是指執行方法後獲取方法丟擲異常後,@AfterReturning是指在執行方法後呼叫,@AfterThrowing是指方法丟擲異常後呼叫。
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();
}
---------------------
作者:HappyHeng
來源:CSDN
原文:https://blog.csdn.net/happyheng/article/details/53027484
版權宣告:本文為博主原創文章,轉載請附上博文連結!