完全基于注解的Spring5.x的事务的代码Demo

以一个用户新增的功能为例,演示Spring5基于完全注解方式整合事务的例子。


开发环境:JDK8 , Maven 3.5.4 , IDEA 2019.1.2 , MySQL 5.7.x,Spring 5.0.2,Druid 。
涉及的包:service,dao,config
接口:UserService、UserDao ;实现类:UserServiceImpl 、UserDaoImpl。


Maven的依赖pom.xml:



    4.0.0

    tech.jabari
    spring-txn-annotation-demo
    1.0-SNAPSHOT

    
        
            org.springframework
            spring-context
            5.0.2.RELEASE
        
        
            org.springframework
            spring-jdbc
            5.0.2.RELEASE
        
        
            org.springframework
            spring-aspects
            5.0.2.RELEASE
        
        
            mysql
            mysql-connector-java
            5.1.46
        
        
            com.alibaba
            druid
            1.1.12
        
        
            org.projectlombok
            lombok
            1.18.12
        
        
            org.springframework
            spring-test
            5.0.2.RELEASE
        
        
            junit
            junit
            4.12
        
    


src/main/resources:
db.properties文件内容:

jdbc.url=jdbc:mysql://127.0.0.1:3306/exercise01?useUnicode=true&characterEncoding=utf8&useSSL=true 
jdbc.driver=com.mysql.jdbc.Driver 
jdbc.userName=root 
jdbc.password=123456

src/main/java:

User.java代码如下:

package tech.jabari.entity;

import lombok.Data;

import java.util.Date;

@Data
public class User {

    private String name;
    private String pwd;
    private Date  createdTime;

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

    public User() {
    }
}

UserDaoImpl.java代码如下:

package tech.jabari.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import tech.jabari.dao.UserDao;
import tech.jabari.entity.User;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Jabari Lu
 * @title: UserDaoImpl
 * @data 2020/5/28 13:55
 */
@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public int insertUser(User user) {
        String sql = "insert into t_user(name,pwd,created_time)values(?,?,now())";
        Integer ret = jdbcTemplate.update(sql, user.getName(), user.getPwd());
        return ret;
    }
}

UserServiceImpl.java代码如下:

package tech.jabari.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.jabari.dao.UserDao;
import tech.jabari.entity.User;
import tech.jabari.service.UserService;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Transactional(propagation = Propagation.REQUIRED)
    public Integer addUser(User user) {
        int ret = userDao.insertUser(user);
        //模拟异常!
        int x = 1/10;
        return ret;
    }
}
package tech.jabari.spring.txn.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;

@Configuration
@ComponentScan("tech.jabari")
@EnableAspectJAutoProxy
@Import({DataSourceConfig.class,TxnConfig.class})
public class AppConfig {


}
package tech.jabari.spring.txn.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@PropertySource("db.properties")
public class DataSourceConfig {

    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.userName}")
    private String userName;
    @Value("${jdbc.password}")
    private String pwd;

    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driver);
        dataSource.setUsername(userName);
        dataSource.setPassword(pwd);
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }



}
package tech.jabari.spring.txn.config;

import org.aspectj.lang.annotation.AdviceName;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;


@Configuration
@EnableTransactionManagement
/*@Aspect*/
public class TxnConfig {

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    /*@Pointcut("execution(* tech.jabari.service..*.*(..))")
    public void pointcut(){

    }*/


}
src/test/java:
测试类代码:
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 tech.jabari.entity.User;
import tech.jabari.service.UserService;
import tech.jabari.spring.txn.config.AppConfig;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={AppConfig.class})
public class UserServiceAnnoTest {
    @Autowired
    private UserService userService;

    @Test
    public void testAddUser() {
        User user = new User("张三", "pwd123");
        userService.addUser(user);
        System.out.println("------新增用户:[" + user.getName() + "]成功!");
    }

}

 

你可能感兴趣的:(Spring)