Spring AOP

Spring AOP 事務管理  

1. 教學目標
理解AOP的基本原理 
掌握自定義Spring AOP的方法 
熟練掌握Spring有關事務等AOP的配置和使用 
掌握自定義Spring AOP的方法 
掌握Spring與Hibernate集成和使用方法 

2. AOP介紹

AOP,Aspect Oriented Programming,面向方面編程。 

AOP原理下面介紹。 

AOP的作用:對程序解藕和關注分離。 

應用場合: 
事務處理 
權限控制 
審計日誌 
其他 

3. 代理模式

Proxy模式,代理模式,是AOP的前身。 

3.1. 簡單代理

示例見:http://spring2demo.googlecode.com/svn/branches/aop_proxy 

3.1.1. 需求

功能需求: 

爲ProductDaoImpl的save方法增加授權檢查功能 

爲ProductDaoImpl的save方法增加事務的處理功能 

爲ProductDaoImpl的save方法增加打開關閉連接的功能 

系統需求: 

Dao實現應該不管怎麼獲得Connection, 因爲Connection有可能通過數據庫驅動, 也可能通過jndi等獲得; 

Dao實現應該不管事務的處理, 因爲多個Dao方法可能組成一個原子事務; 

Dao實現應該不管誰有權限訪問. 

Dao實現應該專注於有關sql的查詢和操作等. 

這種思路就是關注分離 

3.1.2. 實現

實現代理模式的一般形式: 

 

使用工廠模式和單例模式集成,見ProductDaoFactory 

切換行號顯示切換行號顯示 
  1 public abstract class ProductDaoFactory {
  2 
  3 private static ProductDao productDao;
  4 
  5 public static ProductDao getProductDao() {
  6 if (productDao == null) {
  7 productDao = new ProductDaoTransactionProxy(new ProductDaoImpl());
  8 productDao = new ProductDaoConnectionProxy(productDao);
  9 productDao = new ProductDaoAuthorizationProxy(productDao);
  10 }
  11 
  12 return productDao;
  13 }

調用順序: 

 

代理對調用者是透明的: 

 

代理是可以級聯的 

3.2. 動態代理

見示例:https://spring2demo.googlecode.com/svn/branches/aop_dynaproxy 

簡單代理模式實現的缺點: 
產生大量的代理類 
產生的代理類較難複用給其他類複用 

動態代理解決了簡單代理的問題。 

動態代理實現的方式: 
通過java.lang.reflect包中的動態代理支持 
通過類的繼承(使用類的繼承和cglib庫) 

4. AOP概念

是對代理模式運用的理論化和實現機制的完善. 

見下面的圖: 

 
target object: 目標對象 
aspect: 切面 
joinpoint: 連接點, 切面切入的點 
pointcut: 配合連接點, 說明連接點的斷言和表達式 
advice: 通知, 在連接點要執行的代碼 

通知的種類: 
前置通知 
返回後通知 
拋出異常後通知 
後通知 
環繞通知 

5. Spring的自定義AOP

5.1. 準備工作

類庫: 
lib\asm\*.jar 
lib\aspectj\*.jar 

修改配置文件的schema部分 

<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-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

5.2. 使用模式的AOP

見示例:http://spring2demo.googlecode.com/svn/branches/aop_schema 

修改配置文件的schema部分: 

<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-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

將目標對象和切面對象配置爲bean: 

  <bean id="productDaoTarget"
  class="com.googlecode.spring2demo.aop.spring.schema.ProductDaoImpl" />
  <bean id="authorizationAspect"
  class="com.googlecode.spring2demo.aop.spring.schema.AuthorizationAspect" />
  <bean id="jdbcConnectionAspect"
  class="com.googlecode.spring2demo.aop.spring.schema.JdbcConnectionAspect" />
  <bean id="transactionAspect"
  class="com.googlecode.spring2demo.aop.spring.schema.TransactionAspect" />

配置AOP: 

  <aop:config>
  <aop:pointcut id="productDaoPointcut"
  expression="execution(* com.googlecode.spring2demo.aop.spring.schema.ProductDao.save(..))" />
  <aop:aspect id="authorization" ref="authorizationAspect">
  <aop:before pointcut-ref="productDaoPointcut"
  method="checkAuthorization" />
  </aop:aspect>
  <aop:aspect id="jdbcConnection" ref="jdbcConnectionAspect">
  <aop:before pointcut-ref="productDaoPointcut"
  method="doConnection" />
  <aop:after pointcut-ref="productDaoPointcut"
  method="closeConnection" />
  </aop:aspect>
  <aop:aspect id="transaction" ref="transactionAspect">
  <aop:around pointcut-ref="productDaoPointcut"
  method="doTransaction" />
  <aop:after-throwing pointcut-ref="productDaoPointcut"
  method="doRollback" />
  </aop:aspect>
  </aop:config>

<aop:config>標籤: AOP配置標籤 

<aop:pointcut>標籤: 設置切入點, expression表達式, execution(* spring.aop.schema.ProductDao.save(..)) 

<aop:aspect>標籤: 設置切面 

<aop:aroud>/<aop:after-throwing>/<aop:before >/<aop:after>: 通知 

5.3. 使用註釋的AOP

見示例:http://spring2demo.googlecode.com/svn/branches/aop_annotation 

配置啓用@Aspectj支持 

<aop:aspectj-autoproxy />

配置bean 

  <bean id="productDaoTarget"
  class="com.googlecode.spring2demo.aop.spring.annotation.ProductDaoImpl" />
  <bean id="authorizationAspect"
  class="com.googlecode.spring2demo.aop.spring.annotation.AuthorizationAspect" />
  <bean id="jdbcConnectionAspect"
  class="com.googlecode.spring2demo.aop.spring.annotation.JdbcConnectionAspect" />
  <bean id="transactionAspect"
  class="com.googlecode.spring2demo.aop.spring.annotation.TransactionAspect" />

配置切面和切入點: 

切換行號顯示切換行號顯示 
  1 @Aspect
  2 public class AuthorizationAspect {
  3 
  4 @Before("execution(* com.googlecode.spring2demo.aop.spring.annotation.ProductDao.save(..))")
  5 public void checkAuthorization() {
  6 System.out.println("檢查是否有權限");
  7 }
@Aspect: 切面 

@Before/@After/@Around/@AfterThrowing: 通知 

5.4. AOP聲明風格的選擇

一般儘量選擇註釋風格. 

除非: 運行在java 5之前的jdb版本. 

註釋風格的優點: 
DRY原則: Don't Repeat Yourself, 不要重複自己. 模式風格, 需求的實現分割爲類的聲明和xml配置文件. 
註釋風格可以表示模式風格不能表達的複雜限制 
可以兼容Spring AOP和AspectJ 

6. Spring的事務管理

6.1. 事務隔離級別

預備知識: 
髒讀(dirty reads)一個事務讀取了另一個未提交的並行事務寫的數據。 
不可重複讀(non-repeatable reads) 一個事務重新讀取前面讀取過的數據, 發現該數據已經被另一個已提交的事務修改過。 
幻讀(phantom read) 一個事務重新執行一個查詢,返回一套符合查詢條件的行, 發現這些行因爲其他最近提交的事務而發生了改變. 當一個事務在某一表中進行數據查詢時,另一事務恰好插入了滿足了查詢條件的數據行。則前一事務在重複讀取滿足條件的值時,將得到一個額外的“影象“值。 

事務隔離級別: 
ISOLATION_DEFAULT: 使用數據庫默認的事務隔離級別; 
ISOLATION_READ_UNCOMMITTED: 最低的隔離級別, 允許別外一個事務可以看到這個事務未提交的數據. 可能產生髒讀, 不可重複讀和幻像讀. 
ISOLATION_READ_COMMITTED: 保證一個事務修改的數據提交後才能被另外一個事務讀取. 避免髒讀出現, 但是可能會出現不可重複讀和幻像讀. 
ISOLATION_REPEATABLE_READ: 防止髒讀, 不可重複讀. 
ISOLATION_SERIALIZABLE: 事務被處理爲順序執行.除了防止髒讀, 不可重複讀外, 還避免了幻像讀. 

6.2. 事務傳播類型

PROPAGATION_REQUIRED: 如果存在一個事務, 則支持當前事務. 如果沒有事務則開啓一個新的事務.<--常用 

PROPAGATION_SUPPORTS: 如果存在一個事務, 支持當前事務. 如果沒有事務, 則非事務的執行.<--常用 
PROPAGATION_MANDATORY: 如果已經存在一個事務, 支持當前事務. 如果沒有一個活動的事務, 則拋出異常. 

PROPAGATION_REQUIRES_NEW: 總是開啓一個新的事務. 如果一個事務已經存在, 則將這個存在的事務掛起.<--嵌套事務 
PROPAGATION_NOT_SUPPORTED: 總是非事務地執行, 並掛起任何存在的事務 
PROPAGATION_NEVER: 總是非事務地執行, 如果存在一個活動事務, 則拋出異常 

PROPAGATION_NESTED: 如果一個活動的事務存在, 則運行在一個嵌套的事務中. 如果沒有活動事務, 則按TransactionDefinition.PROPAGATION_REQUIRED 屬性執行. 

6.3. 事務管理的方式

聲明式事務管理: 推薦使用 
<tx:advice id="transactionAdvice"
  transaction-manager="transactionManager">
  <tx:attributes>
  <tx:method name="save*" propagation="REQUIRED" />
  <tx:method name="create*" propagation="REQUIRED" />
  <tx:method name="update*" propagation="REQUIRED" />
  <tx:method name="delete*" propagation="REQUIRED" />
  <tx:method name="*" propagation="SUPPORTS" read-only="true" />
  </tx:attributes>
</tx:advice>
 
編程式事務管理: 
切換行號顯示切換行號顯示 
  1 DefaultTransactionDefinition def = new DefaultTransactionDefinition();
  2 def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
  3 
  4 TransactionStatus status = txManager.getTransaction(def);
  5 try {
  6 // execute your business logic here
  7 }
  8 catch (MyException ex) {
  9 txManager.rollback(status);
  10 throw ex;
  11 }
  12 txManager.commit(status);
  13 
  14  

7. Spring集成Hibernate

見示例:http://spring2demo.googlecode.com/svn/tags/sh_r1_2 

7.1. Spring的高級功能

7.1.1. 多配置文件的import機制

見:test.config.xml 

  <!-- 導入其他組件的配置 -->
  <import
  resource="classpath:com/googlecode/spring2demo/dao/config.xml" />
  <import
  resource="classpath:com/googlecode/spring2demo/product/config.xml" />

7.1.2. 使用properties文件

見:test.config.xml 

  <!-- 屬性文件 -->
  <bean id="propertyConfigurer"
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location">
  <value>
  classpath:com/googlecode/spring2demo/product/config.properties
  </value>
  </property>
  </bean>
這裏是測試使用,一般properties放在classpath根下。 

7.1.3. 對測試代碼的IOC

見代碼:ProductActionTest 

切換行號顯示切換行號顯示 
public class ProductActionTest extends
  AbstractDependencyInjectionSpringContextTests {

  private ProductAction productAction;

  public void setProductAction(ProductAction productAction) {
  this.productAction = productAction;
  }

  @Override
  protected String[] getConfigLocations() {
  return new String[] { "classpath:com/googlecode/spring2demo/product/test.config.xml" };
  }

  @Test
  public void test() throws IOException {
  this.productAction.saveAll();
  }

繼承AbstractDependencyInjectionSpringContextTests 
覆蓋protected String[] getConfigLocations()方法 

7.2. Spring集成Hibernate

7.2.1. 基本的集成步驟

7.2.1.1. 代碼的處理

編寫HibernateDao類,繼承org.springframework.orm.hibernate3.support.HibernateDaoSupport 

編寫有關增刪改查方法,使用超類的HibernateTemplate: 

切換行號顯示切換行號顯示 
  1 public void saveOrUpdate(T entity) {
  2 this.getHibernateTemplate().saveOrUpdate(entity);
  3 }

複雜處理,需要HibernateTemplate.execute()方法,方法參數是HibernateCallback接口。 

HibernateCallback是回調接口,需要實現:public Object doInHibernate(Session session)方法。 

比如: 

切換行號顯示切換行號顯示 
  1 pagination.setRecordSum((Integer) this.getHibernateTemplate().execute(
  2 new HibernateCallback() {
  3 
  4 public Object doInHibernate(Session session)
  5 throws HibernateException, SQLException {
  6 Criteria criteria = session.createCriteria(type);
  7 criteriaCallBack.setCriteria(criteria);
  8 Integer count = (Integer) criteria.setProjection(
  9 Projections.count(Projections.id().toString()))
  10 .uniqueResult();
  11 return count;
  12 }
  13 }));

HibernateTemplate封裝Hibernate Session對象,並做了增強和簡化。 

7.2.1.2. 配置文件

配置datasource: 

  <!-- 有關datasource的配置 -->
  <bean id="dataSource"
  class="com.mchange.v2.c3p0.ComboPooledDataSource"
  destroy-method="close">
  <property name="driverClass" value="${driverClass}" />
  <property name="jdbcUrl" value="${jdbcUrl}" />
  <property name="user" value="${user}" />
  <property name="password" value="${password}" />

  <property name="initialPoolSize" value="1" />
  </bean>

配置hibernate映射文件的列表: 

  <!-- 有關hibernate映射文件的配置 -->
  <bean id="mappingResources" class="java.util.ArrayList">
  <constructor-arg>
  <list>
  <value>
  com/googlecode/spring2demo/product/entity.hbm.xml
  </value>
  </list>
  </constructor-arg>
  </bean>

配置sessionFactory: 

  <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="mappingResources" ref="mappingResources" />
  <property name="lobHandler">
  <bean class="org.springframework.jdbc.support.lob.DefaultLobHandler" />
  </property>
  <property name="hibernateProperties">
  <props>
  <prop key="hibernate.dialect">
  ${hibernate.dialect}
  </prop>
  <prop key="hibernate.cache.use_query_cache">false</prop>
  <prop key="hibernate.show_sql">
  ${hibernate.show_sql}
  </prop>
  <prop key="hibernate.cache.provider_class">
  org.hibernate.cache.NoCacheProvider
  </prop>
  <prop key="hibernate.hbm2ddl.auto">
  ${hibernate.auto}
  </prop>
  </props>
  </property>
  <property name="schemaUpdate">
  <value>${hibernate.schemaUpdate}</value>
  </property>
  </bean>

配置事務管理器: 

  <!-- 事務管理配置 -->
  <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
  </bean>

配置抽象的dao Bean: 

  <!-- Dao實現 -->
  <bean id="dao" class="com.googlecode.spring2demo.dao.HibernateDao" abstract="true">
  <property name="sessionFactory" ref="sessionFactory" />
  </bean>

配置具體的dao Bean: 

  <bean name="productDao"
  class="com.googlecode.spring2demo.product.ProductDaoImpl" parent="dao">
  <property name="type"
  value="com.googlecode.spring2demo.product.Product" />
  </bean>

7.2.2. 事務的處理

使用基於annotation的事務處理方式。 

spring爲事務處理定製了更爲簡潔的annotation。 

在配置文件中: 

<tx:annotation-driven />

在需要事務的接口或者實現類的方法加入annotation 

切換行號顯示切換行號顯示 
  1 /**
  2 * 更新對象
  3 * 
  4 * @param entity
  5 */
  6 @Transactional(propagation = Propagation.REQUIRED)
  7 public void update(T entity);
  8 
  9 /**
  10 * 通過id得到對象
  11 * 
  12 * @param id
  13 * @return
  14 */
  15 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
  16 public T findById(PK id);

通過日誌理解事務的創建和提交過程。 

7.2.3. Lob字段的處理

hibernate可以處理lob字段。 

使用Spring可以更加方便。 

實體類:Photo 

切換行號顯示切換行號顯示 
  1 public class Photo {
  2 private String id;
  3 
  4 private String fileName;
  5 
  6 private String contentType;
  7 
  8 private byte[] data;

Hibernate映射文件: 

  <class name="Photo">
  <id name="id">
  <generator class="uuid" />
  </id>
  <property name="fileName" />
  <property name="contentType" />
  <property name="data"
  type="org.springframework.orm.hibernate3.support.BlobByteArrayType"
  length="1024000" />
  </class>

Spring配置文件: 

  <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="mappingResources" ref="mappingResources" />
  <property name="lobHandler">
  <bean class="org.springframework.jdbc.support.lob.DefaultLobHandler" />
  </property>
如果是oracle 9i等,需要另外的lobHandler配置。 

7.2.4. 通用DAO增強的分頁查詢功能

通用DAO增強的分頁查詢功能:理論上,可以對複雜條件查詢和分頁,其中複雜條件由用戶設置。 

自定義回調接口:CriteriaCallBack 

切換行號顯示切換行號顯示 
  1 public interface CriteriaCallBack {
  2 
  3 /**
  4 * Sets the criteria.
  5 * 
  6 * @param criteria
  7 * the criteria
  8 */
  9 public void setCriteria(Criteria criteria);

使用CriteriaCallBack接口的查詢示例: 

切換行號顯示切換行號顯示 
  1 Pagination<Product>pagination=new Pagination<Product>();
  2 pagination.setNo(1);
  3 pagination.setSize(10);
  4 pagination.setConditon(new CriteriaCallBack(){
  5 @Override
  6 public void setCriteria(Criteria criteria) {
  7 Product product=new Product();
  8 product.setName("1");
  9 product.setIntroduction("1");
  10 criteria.add(Example.create(product).enableLike(MatchMode.ANYWHERE).excludeProperty("price"));
  11  
  12 }
  13 });
  14  
  15 this.productAction.browse(pagination);
  16  
  17 assert pagination.getResults().size()==1;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章