文章目录
springboot项目如何开启事务?
针对这个问题,一部分小伙伴肯定回答的比较迅速,启动类上加上@EnableTransactionManagement注解,在需要事务支持的方法或者类或者接口的抽象方法或者接口类上加上@Transactional注解。这个回答没什么大问题,项目可以正常启动,事务支持也正常。但针对springboot项目,其实正常情况下是不需要在启动类上面加上@EnableTransactionManagement注解的。
原理
springboot项目可以不加@EnableTransactionManagement注解,是归功于springboot的自动配置功能。springboot旨在简化spring项目的配置,不管是基于注解的配置,还是以前的基于xml的配置,所以springboot项目在启动的时候会自动给我们加载很多的配置类,其中就有一个跟事务相关的自动配置类org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration。
代码展示
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.transaction;
import java.util.stream.Collectors;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org