前面使用Spring xml配置文件实现实现事务,现将xml文件替换成Spring配置类。

applicationContext.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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx" 
       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/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd 
       http://www.springframework.org/schema/aop 
       https://www.springframework.org/schema/aop/spring-aop.xsd
">

    <!--加載數據庫配置文件,讀取文件中數據-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>

    <!--開啟自動掃描-->
    <context:component-scan base-package="com.company"/>

    <!--
     Spring的事務管理器PlatformTransactionManager接口實現類
     事務管理依賴連接對象
     注入數據源
    -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
    </bean>

    <aop:aspectj-autoproxy/>

    <!--
    配置事務的屬性 advice通知 橫切邏輯
    切入是事務管理
    -->
    <tx:advice id="adviceId" transaction-manager="transactionManager">
        <tx:attributes>
            <!--
            方法:給哪個方法添加事務 name方法名字
            *所有方法使用
            事務:只讀(查詢) 非只讀(增刪改)
            name="*" read-only="false" 所有方法的事務都是非只讀
            isolation:事務隔離級別 默認級別,不寫就是默認
            REQUIRED:你無事務,我創建,你有事務,我融合。非只讀
            propagation:傳播行為
            rollback-for:屬性指的是,遇到哪些異常回滾,寫異常類名,全名,多個之間逗號
            no-rollback-for:哪些異常不回滾

            -->
            <tx:method name="*" read-only="false" propagation="REQUIRED" timeout="-1" ></tx:method>
            <!--
            配置只讀事務
            查詢方法:某個開頭 query get select
            -->
            <tx:method name="query*" read-only="true" propagation="SUPPORTS"></tx:method>
        </tx:attributes>
    </tx:advice>

    <!--事務配置-->
    <aop:config>
        <!--
        事務通知增強, advice-ref配置事務屬性的id
        事務通知,基本是固定方位用法,環繞通知
        -->
        <aop:advisor advice-ref="adviceId" pointcut="execution(* com.company.service.AccountServiceImpl.*(..))"></aop:advisor>
    </aop:config>


    <!--配置DriverManagerDataSource Bean,并注入屬性值-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--配置JdbcTemplate Bean,并注入dataSource-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
    </bean>
</beans>

基于前面的代码,变动的部分如下:

config目录下SpringConfig.java

@Configuration  //表明此类是Spring 配置类
@ComponentScan("com.company")  //开启自动扫描,将注解的Bean放入IOC容器中
@PropertySource({"classpath:db.properties"}) //加载资源文件
@EnableAspectJAutoProxy  //启动切片管理
@EnableTransactionManagement  //事务管理
public class SpringConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean("dataSource")
    public DataSource getDataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean("jdbcTemplate")
    public JdbcTemplate getJdbcTemplate(@Qualifier("dataSource") DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }

    @Bean("transactionManager")
    public PlatformTransactionManager getPlatformTransactionManager(@Qualifier("dataSource") DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
        return dataSourceTransactionManager;
    }
}

service目录下AccountService.java

/***
 * 事務管理的註解
 * 加載接口上,所有實現類都應用
 */
@Transactional
public interface AccountService {
    void updateAccount(Account account);
    void transfer(String fromAccount,String toAccount,float money);
}

测试

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
//设置Spring 配置数据 在SpringConfig类里
@ContextConfiguration(classes = {SpringConfig.class})
@ComponentScan("com.company")
public class JdbcTemplateTransaction {
    @Autowired
    @Qualifier("accountService")
    private AccountService accountService;

    @Test
    public void transfer(){
        accountService.transfer("march","feb",500f);
    }
}

 

 posted on 2019-10-28 22:06  会飞的金鱼  阅读(689)  评论(0)    收藏  举报