1.Spring AOP簡介
AOP (Aspect Oriented Programming)面向切面編程
OOP(Oriented Oriented Programming)面向?qū)ο缶幊?br>
通過OOP的縱向和AOP的橫向抽取函卒,程序才可以真正解決問題
AOP的使用場(chǎng)景:日志 事務(wù)
2.AOP的核心概念
Aspect(切面)
Join Point(連接點(diǎn))
Advice(通知/增強(qiáng))
Pointcut(切點(diǎn))
Introduction(引入)
Target Object(目標(biāo)對(duì)象)
AOP Proxy(AOP代理)
Weaving(織入)
3.HelloWorld前置增強(qiáng)練習(xí)
給pom文件中添加aop依賴
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>{aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
Hello接口類
package com.spring.aop;
public interface Hello {
String getHello();
}
HelloImpl類
package com.spring.aop;
public class HelloImpl implements Hello {
@Override
public String getHello() {
return "Hello,Spring AOP";
}
}
用戶自定義的前置增強(qiáng)類MyBeforeAdvicelei
package com.spring.aop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
- 用戶自定義的前置增強(qiáng)類
-
/
public class MyBeforeAdvice {
private static final Logger logger= LoggerFactory.getLogger(MyBeforeAdvice.class);
/定義前置方法*/
public void beforeMethod() {
logger.info("This is a before method by wxy");
logger.debug("This is a before method by wxy");
//System.out.println("This is a before methoad");
}
}
用日志記錄方法
配置文件
<!--配置一個(gè)Hello的bean 等同于Hello hello = new HelloImpl();-->
<bean id="hello" class="com.spring.HelloImpl"/>
<!--配置一個(gè)MyBeforeAdvice前置增強(qiáng)的bean-->
<bean id="mybeforeAdvice" class="com.spring.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>
HelloApp主類
package com.spring.aop;
import javafx.application.Application;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("/bean.xml");
Hello hello = context .getBean(Hello.class);
System.out.println(hello.getHello());
}
}