spring aop

目录
教学目标
AOP介绍
代理模式
简单代理
需求
实现
动态代理
AOP概念
Spring的自定义AOP
准备工作
使用模式的AOP
使用注释的AOP
AOP声明风格的选择
Spring的事务管理
事务隔离级别
事务传播类型
事务管理的方式
Spring集成Hibernate
Spring的高级功能
多配置文件的import机制
使用properties文件
对测试代码的IOC
Spring集成Hibernate
基本的集成步骤
代码的处理
配置文件
事务的处理
Lob字段的处理
通用DAO增强的分页查询功能
练习和作业

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;

8. 练习和作业

独立完成课上的示例。 

work/training/java/jee/spring/aop (2008-04-08 08:27:19由marshal编辑)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值