Java57spring:转账业务,web工程监听器

Posted 码农编程录

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java57spring:转账业务,web工程监听器相关的知识,希望对你有一定的参考价值。


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

    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
       <!-- <property name="jdbcTemplate" ref="jdbcTemplate"></property>-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
    </bean>-->

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="url" value="${jdbc.url}"></property>
    </bean>

    <!-- spring事务的配置步骤
        1.在applicationContext.xml中配置事务管理器的bean
        2.配置事务的策略
        3.配置事务的aop
    -->
    <!--
        声明对于jdbc进行事务管理的 事务管理器对象
        id建议叫做  transactionManager,如果不叫这个名字,我们配置策略是,需要指定事务管理器对象的名字
    -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>


    <!--
        配置spring事务的策略
        tx:advice:声明开始配置事务的策略
            id:当前策略的唯一标识
            transaction-manager: 指定事务管理器对象。默认值为transactionManager
    -->
    <tx:advice id="tx1" >
        <!-- 声明具体的策略 -->
        <tx:attributes>
            <!--
                tx:method : 指定对于哪些方法进行事务的管理
                        name:方法名的表达式
                        read-only: 事务是否只读,默认是false
                        timeout:超时时间,默认为-1,永不超时。
                        isolation: 事务的隔离级别,默认采用数据库默认的隔离级别
                        propagation: 事务的传播行为
                        rollback-for="": 针对指定的异常进行回滚
                        no-rollback-for="": 针对指定的异常不进行回滚
            -->
            <tx:method name="*" />
           <!-- <tx:method name="select*" read-only="true"/>-->
        </tx:attributes>
    </tx:advice>


    <!-- 配置事务的aop
        AspectJ 表达式的语法  修饰符 返回值 包名.类型.方法名()
    -->
    <aop:config>
        <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut>
        <!--
            advice-ref="tx1":使用哪个策略
            pointcut-ref="pt1" : 事务切入到哪个切入点
        -->
        <aop:advisor advice-ref="tx1" pointcut-ref="pt1"></aop:advisor>
    </aop:config>
</beans>

2.spring的半xml半注解方式配置事务

ioc注解要用包扫描开启ioc注解,aop也要开启,事务也要开启,

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

    <!-- bean definitions here -->

    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>



    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
    </bean>


    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="url" value="${jdbc.url}"></property>
    </bean>


    <!--
        1.开启注解方式的事务
        2.开启ioc注解
        3.在service层的实现类上添加@Transactional 即可

             @Transactional: 即可用在方法上,也可用在实现类上,也可用在接口上。
                    执行方法是,寻找的顺序是   方法->实现类->接口
                  如果需要配置事务的信息,那么直接通过@Transactional注解的相关属性去配置事务的策略信息
    -->

    <context:component-scan base-package="com.itheima"></context:component-scan>
    <tx:annotation-driven></tx:annotation-driven>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>


</beans>
package com.itheima.service.impl;

import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")

public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public Account findAccountByName(String name) {

        return accountDao.findAccountByName(name);
    }

    @Override
    @Transactional
    public void transfer(String outName, String inName, double money) {

        //1.查询用户的账户信息
        Account outAccount = accountDao.findAccountByName(outName);
        Account inAccount = accountDao.findAccountByName(inName);
        //2.转账,
        outAccount.setMoney(outAccount.getMoney()-money);
        inAccount.setMoney(inAccount.getMoney()+money);
        //3.将数据更新到数据库
        accountDao.update(outAccount);
        int i = 1/0;
        accountDao.update(inAccount);

    }
}

3.spring的纯注解方式配置事务

package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
     需要使用一个配置类来代替xml核心配置
     1.创建一个类,通过@Configuration来声明当前类是一个配置类
     2.引入外部配置文件
     3.将jdbcTemplate和dataSource,和事务管理器对象 装配到spring容器中
     4.开启包扫描
     5.开启注解事务
 */
@Configuration
@Import(JdbcConfig.class)
@ComponentScan("com.itheima")
@EnableTransactionManagement  //开启注解事务
public class SpringConfig {
}
package com.itheima.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;

@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
	@Value("${jdbc.username}")
	private String username;
	@Value("${jdbc.password}")
	private String password;
	@Value("${jdbc.url}")
	private String url;
	@Value("${jdbc.driverClass}")
	private String driverClass;
    //下面是三个对象的装配	
	@Bean
	public DataSource dataSource(){
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(driverClass);
		dataSource.setUrl(url);
		dataSource.setPassword(password);
		dataSource.setUsername(username);
		return dataSource;
	}
	@Bean
	public JdbcTemplate jdbcTemplate(DataSource dataSource){
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		return jdbcTemplate;
	}
	@Bean
	public DataSourceTransactionManager transactionManager(DataSource dataSource){
		DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
		transactionManager.setDataSource(dataSource);
		return transactionManager;
	}
}
package com.itheima.service;
import com.itheima.config.SpringConfig;
import com.itheima.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AccountServiceTest {
    @Autowired
    private AccountService accountService;
    @Test
    public void findAccountByName() {
        Account aaa = accountService.findAccountByName("aaa");
        System.out.println(aaa);
    }
    @Test
    public void transfer(){
        accountService.transfer("aaa","bbb",200);
    }
}

4. 配置文件

//pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.itheima</groupId>
    <artifactId>spring_day04_web</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.6.RELEASE</version>
        </dependency>
        <!--监听器与web相关-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.0.6.RELEASE</version>
        </dependency>
    </dependencies>

    <packaging>war</packaging>
    <build>
        <plugins>
            <!-- java编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
//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"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="userService" class="com.itheima.service.impl.UserServiceImpl">Java框架spring学习笔记(十八):事务操作

Java55spring:AOP

基于 spring boot + mybatis-plus实现简单的转账业务

Java 工程师核心基础

阶段3 2.Spring_07.银行转账案例_4 编写事务管理工具类并分析连接和线程解绑

阶段3 2.Spring_07.银行转账案例_4 编写事务管理工具类并分析连接和线程解绑