SpringBoot的出现使得项目中使用事务变得非常简单,有两种使用方式,适合小型项目的注解事务(声明式事务管理),适合大型项目的全局事务。
1、注解事务。(次要)
注解事务使用只用两步,开启事务注解功能,使用事务注解功能,并且每步都只有使用一个注解。
第一步:开启事务注解功能@EnableTransactionManagement
在主启动类中添加注解@EnableTransactionManagement
即可。
package com.gx;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement //开启事务注解功能
@SpringBootApplication
public class Ch09SpringbootTransAnnoApplication {
public static void main(String[] args) {
SpringApplication.run(Ch09SpringbootTransAnnoApplication.class, args);
}
}
第二步:使用事务注解功能@Transactional
在service接口实现类或接口实现类方法上添加@Transactional
即可。
package com.gx.service.impl;
import com.gx.service.StudentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.gx.domain.Student;
@Service
public class StudentServiceImpl implements StudentService {
@Transactional //使用注解事务
@Override
public String addStudent(Student student) {
//业务方法
}
}
注意事项:@Transactional
必须添加在public修饰的方法上。
2、全局事务。(主要)
SpringBoot全局事务主要使用AOP切面编程。
第一步:创建切面类@Aspect
。
创建一个普通的类,加上@Aspect
后该类就是一个切面类了,用于编写事务功能。同时还需要把该切面类定义为一个配置类,添加注解@Configuration
即可。
注意事项:1、@Aspect
将该类定义为切面类,把当前类作为一个切面被容器读取。
2、@Configuration
将该类定义为配置类,配置spring容器,注入bean
package com.gx.config;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
@Aspect //定义切面类,把当前类标识为一个切面供容器读取
@Configuration //定义配置类
public class TransactionAdviceConfig {
//增强方法
}