@Transaction作用在Controller层或者是service层的配置,解决事务的作用域

本文详细介绍了如何在Spring框架中实现事务管理,包括在Service层和Controller层应用事务的不同配置方法,并强调了事务管理对于保证数据一致性的关键作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,如果在service层加事务

1.事务一般要放在Service层,放在Controller也可以,。

2.在springmvc的配置文件中扫描controller时要忽略service,因为在springmvc的配置文件加载的service事务不起作用。所以在springmvc.xml中:

         

<!-- 扫描web相关的bean 只扫描@controller,忽略service ,因为springmvc扫描的service没有事务-->

<context:component-scan base-package="com.xxx">

<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />

</context:component-scan>

 

spring.xml中扫描@service

<!-- 扫描daoservice,因为spring扫描的service才具有事务功能 -->

<context:component-scan base-package="com.xxx">

</context:component-scan>

 

 3.在service层中的类方法加@Transaction注解即可

 

    前提是:在spring.xml配置了:

    <!-- 事务配置 -->

     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="dataSource" />

    </bean>

 <!-- 使用annotation注解方式配置事务 -->

    <tx:annotation-driven transaction-manager="transactionManager" />

 

二,在Controller层加事务:

将事物加在contrller层,只需要在springmvc.xml中加上<tx:annotation-driven/>即可,也要在扫描包同service一样(上面)并且contrller类中加上@Transactional即可。

前提是在spring.xml中要有事物管理器的配置即

 

 <!-- 事务配置 -->

     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="dataSource" />

    </bean>

 

注意: Controller层只支持 @Transactional 注解式事务!

注意:@Transaction不起作用的:1.静态(static )方法,  2,(private)私有化方法,   3,自调用方法(因为事务是依赖aop的,而aop是通过动态代理实现的),   

参考:https://blog.youkuaiyun.com/tongyu75/article/details/53323892

package com.lx.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import javax.sql.DataSource; public class jdbcConfig { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean public DataSource dataSource(){ DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } @Bean public PlatformTransactionManager transactionManager(DataSource dataSource){ DataSourceTransactionManager ds = new DataSourceTransactionManager(); ds.setDataSource(dataSource); return ds; } } package com.lx.config; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.context.annotation.Bean; import javax.sql.DataSource; public class MybatisConfig { @Bean public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){ SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setTypeAliasesPackage("com.lx.domain"); return factoryBean; } @Bean public MapperScannerConfigurer mapperScannerConfigurer(){ MapperScannerConfigurer msc = new MapperScannerConfigurer(); //接口 msc.setBasePackage("com.lx.dao"); return msc; } } package com.lx.config; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import java.util.logging.Filter; public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer { protected Class<?>[] getRootConfigClasses() { return new Class[]{SpringConfig.class}; } protected Class<?>[] getServletConfigClasses() { return new Class[]{SpringmvcConfig.class}; } protected String[] getServletMappings() { return new String[]{"/"}; } /*protected Filter[] getServletFilters(){ CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setEncoding("UTF-8"); return new Filter[]{filter}; }*/ }package com.lx.config; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import java.util.logging.Filter; public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer { protected Class<?>[] getRootConfigClasses() { return new Class[]{SpringConfig.class}; } protected Class<?>[] getServletConfigClasses() { return new Class[]{SpringmvcConfig.class}; } protected String[] getServletMappings() { return new String[]{"/"}; } /*protected Filter[] getServletFilters(){ CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setEncoding("UTF-8"); return new Filter[]{filter}; }*/ } package com.lx.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @ComponentScan({"com.lx.service"}) @PropertySource("jdbc.properties") @Import({jdbcConfig.class , MybatisConfig.class}) @EnableTransactionManagement public class SpringConfig { } package com.lx.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration @ComponentScan("com.lx.controller") @EnableWebMvc public class SpringmvcConfig { } 对以上五个整合ssm的配置类结合javaweb的几框架做出解释,并总结一下不同配置类之间的关系作用
最新发布
05-28
<think>好的,我现在需要帮用户解释SSM整合中的五个配置类的作用及其关系。用户提到的五个配置类是jdbcConfig、MybatisConfig、ServletConfig、SpringConfig和SpringmvcConfig。首先,我得回忆一下SSM框架整合的基本结构,以及每个配置类通常负责的部分。根据用户提供的引用内容,引用[2]提到了SpringConfig类,里面用@Import导入了JdbcConfig和MyBatisConfig,说明这两个配置类可能是处理数据源和MyBatis相关的配置。而引用[3]中的ServletConfig类处理Servlet组件的注册,比如Servlet、Filter等。SpringmvcConfig应该对应之前的WebConfig,负责SpringMVC的配置,比如视图解析器、拦截器等。 接下来,我需要确定每个配置类的具体作用。JdbcConfig可能包含数据源的配置,比如Druid或HikariCP的连接池设置。MyBatisConfig可能处理SqlSessionFactoryBean、MapperScannerConfigurer等MyBatis相关的Bean。ServletConfig处理嵌入式Servlet容器的组件,这在Spring Boot中常见,但用户可能在普通SSM中使用,所以需要确认是否正确。不过根据用户的问题,他们可能是在传统的SSM整合中使用这些配置类。然后,SpringConfig作为核心配置类,通过组件扫描、属性加载,并整合其他配置类,比如Jdbc和MyBatis的配置。而SpringmvcConfig则专注于控制,处理请求映射、视图解析等。关系方面,SpringConfig作为根配置,负责服务和数据的Bean,而SpringmvcConfig是子配置,处理Web。JdbcConfig和MyBatisConfig被导入到SpringConfig中,ServletConfig可能独立处理Servlet相关的配置,但需要确认是否属于Spring MVC的一部分。 需要检查用户提供的引用,比如引用[3]中的ServletConfig使用了@Configuration,可能属于Spring的配置,但通常Servlet的配置在WebInitializer中处理,或者在SpringBoot中通过配置类。可能需要指出ServletConfig在传统SSM中的位置,是否属于Spring MVC配置的一部分,或者单独存在。总结时,需要明确每个配置类的作用域次结构,以及它们如何协同工作。例如,数据源和事务管理在SpringConfig中,MyBatis的会话工厂在MyBatisConfig,Servlet组件在ServletConfig,MVC相关在SpringmvcConfig。同时,它们之间的依赖关系,比如MyBatisConfig依赖JdbcConfig的数据源,SpringConfig整合所有底配置,SpringmvcConfig处理Web,而ServletConfig可能属于Web的一部分。 最后,确保回答结构清晰,分点说明每个配置类的作用,然后用图示或文字描述它们之间的关系,并添加相关问题,比如如何分离配置、处理多数据源等。</think>### SSM整合中五个核心配置类的作用及关系解析 #### 一、配置作用详解 以下五个配置类构成SSM框架的核心配置体系,其作用域与分对应关系如下: $$ \begin{array}{|c|c|} \hline \text{配置类} & \text{作用域与功能} \\ \hline \text{JdbcConfig} & \text{数据访问配置:数据源(DataSource)、连接池参数、JDBC事务管理器等}[^2] \\ \hline \text{MyBatisConfig} & \text{ORM配置:SqlSessionFactoryBean、Mapper扫描器、MyBatis插件等}[^2] \\ \hline \text{SpringConfig} & \text{核心容器配置:组件扫描、属性加载、整合其他配置类}[^2] \\ \hline \text{SpringmvcConfig} & \text{Web配置:控制器扫描、视图解析器、拦截器等}[^1] \\ \hline \text{ServletConfig} & \text{Servlet容器配置:注册Servlet/Filter/Listener组件}[^3] \\ \hline \end{array} $$ #### 二、分架构中的关系 1. **依赖流向** - `JdbcConfig` $\rightarrow$ `MyBatisConfig`(提供数据源依赖) - `SpringConfig` $\leftarrow$ `JdbcConfig` + `MyBatisConfig`(通过@Import整合) - `SpringmvcConfig` $\perp$ `SpringConfig`(父子容器关系) - `ServletConfig` $\subset$ Web(独立配置Servlet组件) 2. **次对应** ```mermaid graph TD A[SpringConfig] -->|管理| B[Service] A -->|导入| C[JdbcConfig] A -->|导入| D[MyBatisConfig] E[SpringmvcConfig] -->|管理| F[Controller] G[ServletConfig] -->|注册| H[Servlet组件] ``` #### 三、典型配置示例 1. **JdbcConfig.java**(数据源配置) ```java @Configuration public class JdbcConfig { @Value("${jdbc.url}") private String url; @Bean public DataSource dataSource() { DruidDataSource ds = new DruidDataSource(); ds.setUrl(url); return ds; } } ``` 2. **MyBatisConfig.java**(ORM配置) ```java @Configuration public class MyBatisConfig { @Bean public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) { SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); return factory; } } ``` 3. **SpringConfig.java**(核心容器) ```java @Configuration @ComponentScan("com.example.service") @PropertySource("classpath:jdbc.properties") @Import({JdbcConfig.class, MyBatisConfig.class}) @EnableTransactionManagement public class SpringConfig { // 事务管理器配置 @Bean public PlatformTransactionManager transactionManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } } ``` #### 四、配置类交互关系 1. **启动流程** - **Web容器初始化**:通过`WebAppInitializer`加载`SpringmvcConfig`和`SpringConfig`[^1] - **父子容器隔离**:`SpringmvcConfig`仅管理Controller,`SpringConfig`管理Service/DAO - **配置类加载顺序**: $$ \text{SpringConfig} \rightarrow \text{JdbcConfig} \rightarrow \text{MyBatisConfig} \rightarrow \text{SpringmvcConfig} $$ 2. **测试类引用** 单元测试通过`@ContextConfiguration(classes = SpringConfig.class)`加载核心配置[^4] ### 配置类关系总结 $$ \begin{array}{ccc} \text{SpringmvcConfig} & \leftarrow \text{Web} & \\ \uparrow & & \uparrow \\ \text{SpringConfig} & \rightarrow \text{MyBatisConfig} & \rightarrow \text{JdbcConfig} \\ & \downarrow & \\ & \text{DAO/Service} & \end{array} $$
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值