Spring入门(三)

目录

一、Spring的AOP操作

使用Aspectj实现AOP的操作(基于注解)

二、Spring的jdbcTemplate操作数据库

三、Spring配置C3P0连接池

四、Spring的事务管理

(一)概念

(二)Spring事务管理API

(三)声明式事务管理(基于xml)

模拟转账场景

(四)声明式事务管理(基于注解)


一、Spring的AOP操作

Aspectj实现AOP(基于注解)

1、创建基本类

package com.bird.service;

/**
 * @Author:wangqk
 * @Date:2018/11/10 下午6:54
 */
public class UserService {
    public void show() {
        System.out.println("service show ... ");
    }
}

2、创建增强类

package com.bird.service;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

/**
 * 增强类上使用注解实现Aop
 *
 * @Author:wangqk
 * @Date:2018/11/10 下午6:55
 */
@Aspect
public class AopService {
    /**
     * 前置增强
     */
    @Before(value = "execution(* com.bird.service.UserService.show(..))")
    public void before() {
        System.out.println("before ... ");
    }

    /**
     * 后置增强
     */
    @After(value = "execution(* com.bird.service.UserService.show(..))")
    public void after() {
        System.out.println("after ... ");
    }

    /**
     * 环绕增强
     *
     * @param proceedingJoinPoint
     * @throws Throwable
     */
    @Around(value = "execution(* com.bird.service.UserService.show(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("方法执行之前");
        proceedingJoinPoint.proceed();
        System.out.println("方法执行之后");
    }
}

3、创建Spring配置文件

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

    <!-- 创建对象 -->
    <bean id="userService" class="com.bird.service.UserService"/>
    <bean id="aopService" class="com.bird.service.AOPService"/>

    <!-- 开启AOP -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

4、单元测试

package com.bird.service;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Author:wangqk
 * @Date:2018/11/10 下午7:01
 */
public class UserServiceTest {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) context.getBean("userService");
        userService.show();
    }
}

二、Spring的jdbcTemplate操作数据库

(一)增删改

1、导入jar包

2、创建Dao实现数据库操作(增加、删除、修改)

package com.bird.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

/**
 * @Author:wangqk
 * @Date:2018/11/11 下午3:48
 */
public class UserDao {

    /**
     * 保存用户信息
     */
    void saveUser() {
        // 设置数据库信息
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///spring");
        dataSource.setUsername("root");
        dataSource.setPassword("1234567890");

        // 创建jdbcTemplate对象,并设置数据源
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        // 调用jdbcTemplate对象方法实现操作
        String sql = "insert into user values (?,?)";
        int rows = jdbcTemplate.update(sql, "taobao", "11");
        System.out.println(rows);
    }

    /**
     * 更新用户信息
     */
    void updateUser() {
        // 设置数据库信息
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///spring");
        dataSource.setUsername("root");
        dataSource.setPassword("1234567890");

        // 创建jdbcTemplate对象,并设置数据源
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        // 调用jdbcTemplate对象方法实现操作
        String sql = "update user set password = ? where name = ?";
        int rows = jdbcTemplate.update(sql, "456", "zhangsan");
        System.out.println(rows);
    }

    /**
     * 删除用户信息
     */
    void deleteUser() {
        // 设置数据库信息
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///spring");
        dataSource.setUsername("root");
        dataSource.setPassword("1234567890");

        // 创建jdbcTemplate对象,并设置数据源
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        // 调用jdbcTemplate对象方法实现操作
        String sql = "delete from user where name = ?";
        int rows = jdbcTemplate.update(sql, "lisi");
        System.out.println(rows);
    }

}

3、创建Spring配置文件

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

    <!-- 创建对象 -->
    <bean id="userDao" class="com.bird.dao.UserDao"/>
</beans>

4、单元测试

package com.bird.dao;

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;

/**
 * @Author:wangqk
 * @Date:2018/11/11 下午4:27
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext.xml")
public class UserDaoTest {
    @Autowired
    private UserDao userDao;

    @Test
    public void test() {
        userDao.saveUser();
        userDao.updateUser();
        userDao.deleteUser();
    }
}

(二)查

  • 查询返回一个值
  • 查询返回对象
  • 查询返回List集合

1、创建User类(封装查询结果集)

package com.bird.entity;

/**
 * @Author:wangqk
 * @Date:2018/11/11 下午4:54
 */
public class User {
    private String name;
    private String password;

    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

2、创建Dao实现数据库操作(查询)

package com.bird.dao;

import com.bird.entity.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.sql.*;
import java.util.List;

/**
 * @Author:wangqk
 * @Date:2018/11/11 下午3:48
 */
public class UserDao {

    /**
     * 查询返回某一个值
     */
    void queryForOne() {
        // 设置数据库信息
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///spring");
        dataSource.setUsername("root");
        dataSource.setPassword("1234567890");

        // 创建jdbcTemplate对象,并设置数据源
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        // 调用jdbcTemplate对象方法实现操作
        String sql = "select count(1) from user";
        int counts = jdbcTemplate.queryForObject(sql, Integer.class);
        System.out.println(counts);
    }

    /**
     * jdbc底层实现查询返回某一个值
     */
    void queryForOne2() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            // 加载数据库驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 创建连接
            connection = DriverManager.getConnection("jdbc:mysql:///spring", "root", "1234567890");
            // 编写sql
            String sql = "select * from user where name = ?";
            // 预编译sql
            preparedStatement = connection.prepareStatement(sql);
            // 设置参数
            preparedStatement.setString(1, "zhangsan");
            // 执行sql
            resultSet = preparedStatement.executeQuery();
            // 遍历结果集
            while (resultSet.next()) {
                String name = resultSet.getString("name");
                String password = resultSet.getString("password");
                User user = new User(name, password);
                System.out.println(user);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询返回对象
     */
    void queryForObject() {
        // 设置数据库信息
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///spring");
        dataSource.setUsername("root");
        dataSource.setPassword("1234567890");

        // 创建jdbcTemplate对象,并设置数据源
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        // 调用jdbcTemplate对象方法实现操作
        String sql = "select * from user where name = ?";
        User user = jdbcTemplate.queryForObject(sql, new RowMapper<User>() {
            public User mapRow(ResultSet resultSet, int num) throws SQLException {
                // 从结果集中得到数据
                String name = resultSet.getString("name");
                String password = resultSet.getString("password");
                // 数据封装到对象
                return new User(name, password);
            }
        }, "zhangsan");
        System.out.println(user);
    }

    /**
     * 查询返回集合
     */
    void queryForList() {
        // 设置数据库信息
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///spring");
        dataSource.setUsername("root");
        dataSource.setPassword("1234567890");

        // 创建jdbcTemplate对象,并设置数据源
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        // 调用jdbcTemplate对象方法实现操作
        String sql = "select * from user";
        List<User> list = jdbcTemplate.query(sql, new RowMapper<User>() {
            public User mapRow(ResultSet resultSet, int num) throws SQLException {
                // 从结果集中得到数据
                String name = resultSet.getString("name");
                String password = resultSet.getString("password");
                // 数据封装到对象
                return new User(name, password);
            }
        });
        System.out.println(list);
    }

}

3、单元测试

package com.bird.dao;

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;

/**
 * @Author:wangqk
 * @Date:2018/11/11 下午4:27
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext.xml")
public class UserDaoTest {
    @Autowired
    private UserDao userDao;

    @Test
    public void test() {
        userDao.queryForOne();
        userDao.queryForOne2();
        userDao.queryForObject();
        userDao.queryForList();
    }
}

三、Spring配置C3P0连接池

1、导入jar包

2、创建Spring配置文件

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 配置c3p0数据源连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1234567890"></property>
    </bean>

    <!-- 创建Service对象,注入Dao对象属性 -->
    <bean id="userService" class="com.caijiajia.service.UserService">
        <!-- 注入Dao对象 -->
        <property name="dao" ref="userDao"/>
    </bean>

    <!-- 创建Dao对象,注入JdbcTemplate对象属性 -->
    <bean id="userDao" class="com.caijiajia.dao.UserDao">
        <!-- 注入JdbcTemplate对象 -->
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>

    <!-- 创建JdbcTemplate对象,注入dataSource属性 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 注入dataSource -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

3、创建Service、Dao

package com.caijiajia.service;

import com.caijiajia.dao.UserDao;

/**
 * @ClassName:UserService
 * @Description:TODO
 * @Author:chicago
 * @Date:2018/8/26 下午4:26
 * @Version 1.0
 */
public class UserService {
    private UserDao dao;

    public void setDao(UserDao userdao) {
        this.dao = userdao;
    }

    public void add() {
        dao.add();
    }
}
package com.caijiajia.dao;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * @ClassName:UserDao
 * @Description:TODO
 * @Author:chicago
 * @Date:2018/8/26 下午4:26
 * @Version 1.0
 */
public class UserDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void add() {
        String sql = "insert into user values(?,?)";
        jdbcTemplate.update(sql, "taobao", "mayun");
    }
}

4、编写测试类

package com.caijiajia.test;

import com.caijiajia.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @ClassName:Test
 * @Description:单元测试
 * @Author:chicago
 * @Date:2018/8/20 下午8:45
 * @Version 1.0
 */
public class Test {

    @org.junit.Test
    public void add() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService service = (UserService) context.getBean("userService");
        service.add();
    }
}

四、Spring的事务管理

(一)概念

1、什么是事务?

事务是指一组操作,是对数据库操作的最基本单元。

2、事务的特性?

原子性、一致性、隔离性(多个事务之间不会产生影响)、持久性

3、不考虑隔离性时会产生脏读、不可重复读、虚读(幻读)等问题。如何解决?

设置隔离级别。

(二)Spring事务管理API

1、事务管理的两种方式:

  • 编程式事务管理
  • 声明式事务管理
  1. 基于xml配置文件;
  2. 基于注解;

2、事务管理API

事务管理器接口:PlatformTransactionManager(Spring针对不同的DAO层框架提供了不同的实现类)

事务管理器接口实现类说明
org.springframework.jdbc.datasource.DataSourceTransactionManager针对Spring JDBC或iBatis
org.springframework.orm.hibernate5.HibernateTransactionManager针对Hibernate5.0
org.springframework.orm.jpa.JpaTransactionManager针对JPA

(三)声明式事务管理(基于xml)

模拟转账场景

Service

package com.caijiajia.service;

import com.caijiajia.dao.OrderDao;

/**
 * @ClassName:OrderService
 * @Description:TODO
 * @Author:chicago
 * @Date:2018/9/5 下午10:22
 * @Version 1.0
 */
public class OrderService {

    private OrderDao orderDao;

    public void setOrderDao(OrderDao orderDao) {
        this.orderDao = orderDao;
    }

    public void accountMoney() {
        orderDao.lessMoney();

        orderDao.moreMoney();
    }
}

Dao

package com.caijiajia.dao;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * @ClassName:OrderDao
 * @Description:TODO
 * @Author:chicago
 * @Date:2018/9/5 下午10:22
 * @Version 1.0
 */
public class OrderDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void lessMoney() {
        String sql = "update account set salary=salary-? where name=?";
        jdbcTemplate.update(sql, 1000, "zhangsan");
    }

    public void moreMoney() {
        String sql = "update account set salary=salary+? where name=?";
        jdbcTemplate.update(sql, 1000, "lisi");
    }
}

spring核心配置

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

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="1234567890"></property>
    </bean>

    <bean id="orderService" class="com.caijiajia.service.OrderService">
        <property name="orderDao" ref="orderDao"/>
    </bean>

    <bean id="orderDao" class="com.caijiajia.dao.OrderDao">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>

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


</beans>

测试代码

package com.caijiajia.test;

import com.caijiajia.service.OrderService;
import com.caijiajia.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @ClassName:Test
 * @Description:单元测试
 * @Author:chicago
 * @Date:2018/8/20 下午8:45
 * @Version 1.0
 */
public class Test {

    @org.junit.Test
    public void testAccount() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        OrderService service = (OrderService) context.getBean("orderService");
        service.accountMoney();
    }
}

运行结果

模拟异常

package com.caijiajia.service;

import com.caijiajia.dao.OrderDao;

/**
 * @ClassName:OrderService
 * @Description:TODO
 * @Author:chicago
 * @Date:2018/9/5 下午10:22
 * @Version 1.0
 */
public class OrderService {

    private OrderDao orderDao;

    public void setOrderDao(OrderDao orderDao) {
        this.orderDao = orderDao;
    }

    public void accountMoney() {
        orderDao.lessMoney();

        // 模拟异常
        int i = 10 / 0;

        orderDao.moreMoney();
    }
}

运行结果

解决方案:配置事务回滚操作!!!

步骤:

  1. 配置事务管理器;
  2. 配置事务增强;
  3. 配置切面;
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="1234567890"></property>
    </bean>

    <bean id="orderService" class="com.caijiajia.service.OrderService">
        <property name="orderDao" ref="orderDao"/>
    </bean>

    <bean id="orderDao" class="com.caijiajia.dao.OrderDao">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>

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

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

    <!-- 配置事务增强 -->
    <tx:advice id="txadvice" transaction-manager="transactionManager">
        <!-- 事务的操作 -->
        <tx:attributes>
            <!-- 事务操作方法的匹配规则 -->
            <tx:method name="account*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置切面 -->
    <aop:config>
        <!-- 切入点 -->
        <aop:pointcut id="pointcut" expression="execution(* com.caijiajia.service.OrderService.*(..))"/>
        <!-- 切面 -->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pointcut"/>
    </aop:config>

</beans>

运行结果

(四)声明式事务管理(基于注解)

步骤:

  1. 配置事务管理器;
  2. 配置开启事务注解;
  3. 在使用事务的方法所在类上添加注解;
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
        <property name="username" value="root"></property>
        <property name="password" value="1234567890"></property>
    </bean>
   
    <bean id="orderService" class="com.caijiajia.service.OrderService">
        <property name="orderDao" ref="orderDao"/>
    </bean>

    <bean id="orderDao" class="com.caijiajia.dao.OrderDao">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>

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

    <!-- 1,配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入datasource -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 2,配置开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>
package com.caijiajia.service;

import com.caijiajia.dao.OrderDao;
import org.springframework.transaction.annotation.Transactional;

/**
 * @ClassName:OrderService
 * @Description:TODO
 * @Author:chicago
 * @Date:2018/9/5 下午10:22
 * @Version 1.0
 */
@Transactional
public class OrderService {

    private OrderDao orderDao;

    public void setOrderDao(OrderDao orderDao) {
        this.orderDao = orderDao;
    }

    public void accountMoney() {
        orderDao.lessMoney();

        // 模拟异常
        int i = 10 / 0;

        orderDao.moreMoney();
    }
}

运行结果同上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值