AOP的定義
AOP基本上是通過代理機(jī)制實(shí)現(xiàn)的,他是OOP的延續(xù)也是spring框架中最重要的內(nèi)容之一.
- 定義:運(yùn)行時,動態(tài)地將代碼切入到類的指定方法、指定位置上的編程思想就是面向切面的編程.
- 使用場景:日志、事務(wù)、緩存、調(diào)試等
AOP中基本概念
- Aspect(切面):將關(guān)注點(diǎn)進(jìn)行模塊化.
- Join Point(連接點(diǎn)):在程序執(zhí)行過程中的某個特定的點(diǎn),如謀方法調(diào)用時或處理異常時.
- Advice(通知):在切面的某個特定的連接點(diǎn)上執(zhí)行的動作.
- PointCut(切入點(diǎn)):匹配連接點(diǎn)的斷言.
- Introduction(引入):聲明額外的方法或某個類型的字段.
- Target Object(目標(biāo)對象):被一個或多個切面所通知的對象.
- AOP Proxy(AOP代理):AOP框架創(chuàng)建的對象,用來實(shí)現(xiàn)Aspect Contract包括通知方法執(zhí)行等功能.
- Weaving(織入):把切面連接到其他的應(yīng)用程序類型或?qū)ο笊?并創(chuàng)建一個Advice的對象.
AOP代理
Spring AOP默認(rèn)使用標(biāo)準(zhǔn)的JDK動態(tài)代理來作為AOP的代理,這樣任何接口都可以被代理.
- 使用AspectJ
配置為:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
- 實(shí)際應(yīng)用
public interface Hello {
String getHellow();
}
public class HelloImpl implements Hello{
@Override
public String getHellow() {
return "Hello,spring AOP";
}
}
public class MyBeforeAdvice {
private static final Logger logger= LoggerFactory.getLogger(MyBeforeAdvice.class);
//定義前置方法
public void beforeMethod(){
logger.info("this is a pig");
// System.out.println("this is a before method.");
}
}
<bean id="hello" class="com.spring.aop.HelloImpl"/>
<bean id="myBeforeAdvice" class="com.spring.aop.MyBeforeAdvice"/>
<!--配置aop-->
<aop:config>
<aop:aspect id="before" ref="myBeforeAdvice">
<aop:pointcut id="myPointCut" expression="execution(* com.spring.aop.*.*(..))"/>
<aop:before method="beforeMethod" pointcut-ref="myPointCut"/>
</aop:aspect>
</aop:config>
public class HelloApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("/beans.xml");
Hello hello = context.getBean(Hello.class);
System.out.println(hello.getHellow());
}
}