Spring使用技巧

       总结Spring使用技巧如下:

技巧1:使用ApplicationContextAware得到一个ApplicationContext对象

         Spring容器利用IOC机制初始化创建了对象Bean的实例集合BeanFactory,我们在程序中经常要访问这些Bean实例,一般通过BeanFactory的子类ApplicationContext,最常用的办法就是用ClassPathXmlApplicationContext, FileSystemClassPathXmlApplicationContext, FileSystemXmlApplicationContext 等对象去加载Spring配置文件,这样做也是可以,但是在加载Spring配置文件的时候,就会生成一个新的ApplicaitonContext对象而不是Spring容器帮我们生成的哪一个, 这样就产生了冗余。我们推荐使用的方法是,利用ApplicationContextAware让Spring容器传递自己生成的ApplicationContext,这样我们就可以在程序中引用到自己需要的Bean了。具体方法如下:

        1.建立一个实现ApplicationContextAware接口的类

public class ApplicationContextAccessor implements ApplicationContextAware {  
  •     private static ApplicationContext appCtx;  
  •     /** 
  •      * 此方法可以把ApplicationContext对象inject到当前类中作为一个静态成员变量。 
  •      * @param applicationContext ApplicationContext 对象. 
  •      * @throws BeansException 
  •      */  
  •     @Override  
  •     public void setApplicationContext( ApplicationContext applicationContext ) throws BeansException {  
  •         appCtx = applicationContext;  
  •     }  
  •     /** 
  •      * 这是一个便利的方法,帮助我们快速得到一个BEAN 
  •      * @param beanName bean的名字 
  •      * @return 返回一个bean对象 
  •      */  
  •     public static Object getBean( String beanName ) {  
  •         return appCtx.getBean( beanName );  
  •     }  
  • }  

         2.在spring配置文件中加入如下配置

<bean id="applicationContextAccessor " class="test.ApplicationContextAccessor " />      

        3.在代码中直接引用需要的Bean,方法如下

  BeanExample beanExample= (BeanExample )ApplicationContextAccessor.getBean( "beanExample" );  

       这样我们就可以取得了一个Spring配置的对象, 然后我们就可以自由自在的在程序中享受Spring提供的功能。

 技巧2:事务的配置

注意点:编码的注解方式会影响以下事务控制AOP的执行,如会使事务不会正常回滚。加注解会优先运行产生代码,然后再执行AOP拦截,这样产生的结果就不会正常的执行事务控制了。去掉注解,才会正常执行,这个问题应当注意。找了许多原因才发现的。

方式1:一般AOP方式:

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">

 <!-- 配置DataSource数据源 -->                                                                                                                                                                                                                                                                    
 <bean id="commonDataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://10.12.23.56:3306/ossdb" />
  <property name="username" value="root" />
  <property name="password" value="ceoa2010" />
 </bean>

 <!-- 配置SqlSessionFactoryBean -->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="commonDataSource" />
  <property name="configLocation" value="classpath:mybatis.xml" />
  <!-- mapper和resultmap配置路径 -->
  <property name="mapperLocations">
   <list>
    <value>classpath:cn/zwork/oss/**/*-resultmap.xml</value>
    <value>classpath:cn/zwork/oss/**/*-mapper.xml</value>
   </list>
  </property>
 </bean>

 <!-- 事务配置 -->
 <bean id="transactionManager"
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="commonDataSource" />
 </bean>

 <tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
      <tx:method name="create*" />
      <tx:method name="regist*" />
      <tx:method name="pause*" />
      <tx:method name="stop*" />
   <tx:method name="add*" />
   <tx:method name="delete*" />
   <tx:method name="modify*" />
   
   <tx:method name="search*" read-only='true' />
   <tx:method name="*" />
  </tx:attributes>
 </tx:advice>
 <aop:config>
  <aop:pointcut id="zworkPoint" expression="execution(* cn.zwork..biz..*(..)) " />
  <aop:advisor pointcut-ref="zworkPoint" advice-ref="txAdvice" />
 </aop:config>

 <!-- 分页拦截器 -->

 <!-- 自动扫描mapper的配置 -->
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="cn.zwork" />
  <property name="markerInterface" value="cn.zwork.oss.base.SqlMapper" />
 </bean>
</beans>

方式2:AOP自动代理事务拦截方式:

说明:使用这种方式的原因是,由于项目中采用的mybatis,持久层Mapper调用与“方式1”的AOP方式有冲突,导致事务遇到runtimeException也不能正常回滚,采用这种方式就可以避免这种错误发生,其中bean还不能使用注解方式,要显示的配置spring-bean,才能生效,配置实例如下:

 <bean name="transactionIterceptor"
       class="org.springframework.transaction.interceptor.TransactionInterceptor">
     <property name="transactionManager" ref="transactionManager"></property>  
     <property name="transactionAttributes">                                                                                                                                                                                                                 
      <props>  
        <!--
        凡是涉及DML语句的方法,要求事务传播属性为REQUIRED
        REQUIRED含义:如果无事务,新建;如果有,加入。
   -->
   <prop key="insert*">PROPAGATION_REQUIRED</prop>
   <prop key="create*">PROPAGATION_REQUIRED</prop> 
   <!--
    注:delete*方法的参数:
    +java.lang.RuntimeException代表忽略此方法运行时产生的RuntimeException,
    仍然能够提交,适用于出错日志的数据持久化。
    如果写为:-Exception,代表不忽略任何异常,全部回滚。
    -->
   <prop key="delete*">PROPAGATION_REQUIRED</prop> 
   <prop key="update*">PROPAGATION_REQUIRED</prop>
   <!--
    其他语句可以考虑传播属性为SUPPORTS
    SUPPORTS含义:如果无事务,不新建;如果有,加入。
   -->
   <!--<prop key="find*">PROPAGATION_SUPPORTS</prop> 
   <prop key="get*">PROPAGATION_SUPPORTS</prop>
   <prop key="select*">PROPAGATION_SUPPORTS</prop>
     -->
    </props>  
  </property>  
 </bean>
    
    <!-- AOP方式将事务拦截器织入到需要的结构中 -->
 <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">  
        <property name="beanNames">  
         <!--下面的List中的参数为要求被事务管理器管理的Spring bean的名称  -->
      <list>  
          <value>*Biz</value>  
      </list>  
        </property>  
        <property name="interceptorNames">
            <list><!--  使用的事务拦截器  -->
                 <value>transactionIterceptor</value>  
            </list>  
        </property>
 </bean>

...

<!-- 自动扫描mapper的配置 -->
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="cn.zwork" />
  <property name="markerInterface" value="cn.zwork.oss.base.SqlMapper" />
 </bean>
 
 <bean name="tenantBindClusterBiz" class="cn.zwork.oss.manage.biz.imp.TenantBindClusterBizImp">
 </bean>
 
 <bean name="clusterManagerBiz" class="cn.zwork.oss.manage.biz.imp.ClusterManagerBizImp">
 </bean>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云焰

你的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值