Spring第三天
AOP簡介
什麼是AOP?
AOP(全稱:Aspect Oriented Programming)即面向切面編程,它是面向對象編程OOP的延續,與IOC並稱Spring的兩大核心。在Spring中的主要用於對業務邏輯的各個部分進行隔離,從而使得業務邏輯各個部分之間的耦合度降低,提高程序的可重用性,大大的提高了開發的效率。
AOP的作用以及優勢
作用
在程序運行期間,在不修改源碼的情況下對已有的方法進行增強,也就是使用動態代理的方式。
優勢
- 減少重複代碼
- 提高開發效率
- 維護方便
引入學習案例----給業務層添加事務的支持
業務層代碼
package com.gzgs.service.impl;
import com.gzgs.dao.AccountDao;
import com.gzgs.domain.Account;
import com.gzgs.service.AccountService;
import java.util.List;
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAll() {
return accountDao.findAll();
}
public Account findAccountById(int id) {
return accountDao.findAccountById(id);
}
public void insertAccount(Account account) {
accountDao.insertAccount(account);
}
public void deleteAccount(int id) {
accountDao.deleteAccount(id);
}
public void updateAccount(int id, Account account) {
accountDao.updateAccount(id,account);
}
public void transfer(String sourceName, String targetName, double money) {
//查詢轉出賬戶
Account source = accountDao.findAccountByName(sourceName);
//查詢轉入賬戶
Account target=accountDao.findAccountByName(targetName);
//轉出賬戶扣錢
source.setMoney(source.getMoney()-money);
//轉入賬戶加錢
target.setMoney(target.getMoney()+money);
//更新轉出賬戶
accountDao.updateAccount(source.getId(),source);
//更新轉入賬戶
accountDao.updateAccount(target.getId(),target);
}
}
代理對象工廠代碼
package com.gzgs.factory;
import com.gzgs.service.AccountService;
import com.gzgs.utils.TransactionManager;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 用於創建Service的代理對象工廠
*/
public class BeanFactory {
private AccountService accountService;
private TransactionManager txManager;
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
public void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
public AccountService getAccountService(){
return (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(),
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object rtValue=null;
try {
//開啓事務
txManager.beginTransaction();
//執行操作
rtValue = method.invoke(accountService, args);
//提交事務
txManager.commit();
//返回結果
return rtValue;
}catch (Exception e){
txManager.rollback();
throw new RuntimeException(e);
}finally {
//釋放連接
txManager.release();
}
}
});
}
}
AOP的相關術語
Joinpoint(連接點)
所謂連接點是指那些被攔截到的點。在 spring 中,這些點指的是方法,因爲 spring 只支持方法類型的
連接點,對應上邊的例子就是AccountServiceImpl中所有的方法都是。
Pointcut(切入點)
所謂切入點是指我們要對哪些 Joinpoint 進行攔截的定義,也就是我們需要對其增強的方法。從概念上可以得知,所有的切入點都是連接點,而連接點不一定都是切入點。
Advice(通知/增強)
所謂通知是指攔截到 Joinpoint 之後所要做的事情就是通知。
通知的類型: 前置通知,後置通知,異常通知,最終通知,環繞通知,根據相對與切入點的位置而定。
Introduction(引介)
引介是一種特殊的通知在不修改類代碼的前提下, Introduction 可以在運行期爲類動態地添加一些方
法或 Field。
Target(目標對象)
代理的目標對象,也就是上面例子中的AccountServiceImpl.
Weaving(織入)
是指把增強應用到目標對象來創建新的代理對象的過程。
spring 採用動態代理織入,而 AspectJ 採用編譯期織入和類裝載期織入。
Proxy(代理)
一個類被 AOP 織入增強後,就產生一個結果代理類,也就是上面例子中getAccountService的返回結果。
Aspect(切面)
是切入點和通知(引介)的結合
學習 spring 中的 AOP 要明確的事
開發階段(我們做的)
編寫核心業務代碼(開發主線):大部分程序員來做,要求熟悉業務需求。
把公用代碼抽取出來,製作成通知。(開發階段最後再做): AOP 編程人員來做。
在配置文件中,聲明切入點與通知間的關係,即切面。: AOP 編程人員來做。
運行階段( Spring 框架完成的)
Spring 框架監控切入點方法的執行。一旦監控到切入點方法被運行,使用代理機制,動態創建目標對象的代理對象,根據通知類別,在代理對象的對應位置,將通知對應的功能織入,完成完整的代碼邏輯運行。
在 spring 中,框架會根據目標類是否實現了接口來決定採用哪種動態代理的方式。
基於 XML 的 AOP 配置(改善上面事務控制轉賬案例)
bean.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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置AccountService-->
<bean id="accountService" class="com.gzgs.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置AccountDaoImpl對象-->
<bean id="accountDao" class="com.gzgs.dao.impl.AccountDaoImpl">
<property name="runner" ref="runner"></property>
<!-- 注入ConnectionUtils -->
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<!--配置QuueryRunner對象-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test02"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 配置Connection的工具類 ConnectionUtils -->
<bean id="connectionUtils" class="com.gzgs.utils.ConnectionUtils">
<!-- 注入數據源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事務管理器-->
<bean id="txManager" class="com.gzgs.utils.TransactionManager">
<!-- 注入ConnectionUtils -->
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<!--配置AOP-->
<aop:config>
<!-- 配置切入點表達式 id屬性用於指定表達式的唯一標識。expression屬性用於指定表達式內容
此標籤寫在aop:aspect標籤內部只能當前切面使用。
它還可以寫在aop:aspect外面,此時就變成了所有切面可用
-->
<aop:pointcut id="pt1" expression="execution(* com.gzgs.service.impl.*.*(..))"></aop:pointcut>
<!--配置切面-->
<aop:aspect id="advice" ref="txManager">
<!--配置前置通知-->
<aop:before method="beginTransaction" pointcut-ref="pt1"></aop:before>
<!--配置後置置通知-->
<aop:after-returning method="commit" pointcut-ref="pt1"></aop:after-returning>
<!--配置異常通知-->
<aop:after-throwing method="rollback" pointcut-ref="pt1"></aop:after-throwing>
<!--配置最終通知-->
<aop:after method="release" pointcut-ref="pt1"></aop:after>
</aop:aspect>
</aop:config>
</beans>
基於註解 的 AOP 配置(改善上面事務控制轉賬案例)
在使用基於註解的AOP配置的時候,經常會出現一個後置通知執行異常的bug,這是由於四個通知的調用順序不和邏輯所導致的,調用順序依次是:前置通知,最終通知,後置通知。這樣就會導致由於資源被釋放掉於是導致後置通知執行失敗,通常它的報錯信息是當connection自動提交沒有設置爲false,這是因爲它和前置通知已經不是同一個連接了。所以在使用基於註解的AOP配置的時候,最好是使用環繞通知來控制程序的執行順序。
核心AOP代碼
package com.gzgs.utils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 和事務管理相關的工具類,它包含了,開啓事務,提交事務,回滾事務和釋放連接
*/
@Component("transactionManager")
@Aspect
public class TransactionManager {
@Autowired
private ConnectionUtils connectionUtils;
@Pointcut("execution(* com.gzgs.service.impl.*.*(..))")
private void pt1(){}
/**
* 開啓事務
*/
public void beginTransaction(){
try {
System.out.println("我是前置");
connectionUtils.getThreadConnection().setAutoCommit(false);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 提交事務
*/
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 回滾事務
*/
public void rollback(){
try {
System.out.println("我是異常置");
connectionUtils.getThreadConnection().rollback();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 釋放連接
*/
public void release(){
try {
System.out.println("釋放");
connectionUtils.getThreadConnection().close();//還回連接池中
connectionUtils.removeConnection();
}catch (Exception e){
e.printStackTrace();
}
}
@Around("pt1()")
public Object aroundAdvice(ProceedingJoinPoint pjp){
Object rtValue = null;
try {
//1.獲取參數
Object[] args = pjp.getArgs();
//2.開啓事務
this.beginTransaction();
//3.執行方法
rtValue = pjp.proceed(args);
//4.提交事務
this.commit();
System.out.println("我是後置");
//返回結果
return rtValue;
}catch (Throwable e){
//5.回滾事務
this.rollback();
throw new RuntimeException(e);
}finally {
//6.釋放資源
this.release();
}
}
}
本博客純屬個人學習筆記,學習資源來自黑馬訓練營,如有錯誤,感激指正