SpringConfig.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package space.anyi.config;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import org.mybatis.spring.SqlSessionFactoryBean;
  4. import org.mybatis.spring.mapper.MapperScannerConfigurer;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.context.annotation.*;
  7. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.transaction.PlatformTransactionManager;
  10. import org.springframework.transaction.annotation.EnableTransactionManagement;
  11. import javax.sql.DataSource;
  12. /**
  13. * @fileName: SpringConfig
  14. * @projectName: SSM_template
  15. * @package: space.anyi.config
  16. * @author: 杨逸
  17. * @date:2026/4/24 13:57
  18. * @description: Spring配置类替代spring-context.xml
  19. */
  20. @Configuration // 标识为配置类
  21. @ComponentScan(basePackages = {"space.anyi"},excludeFilters = {@ComponentScan.Filter(value = {Controller.class}, type = FilterType.ANNOTATION)}) // 扫描Service层
  22. @PropertySource("classpath:jdbc.properties") // 加载属性文件
  23. @EnableTransactionManagement // 开启事务管理
  24. public class SpringConfig {
  25. // 配置数据源
  26. @Bean
  27. public DataSource dataSource(@Value("${jdbc.url}") String url,
  28. @Value("${jdbc.username}") String username,
  29. @Value("${jdbc.password}") String password,
  30. @Value("${jdbc.driver}") String driver) {
  31. DruidDataSource dataSource = new DruidDataSource();
  32. dataSource.setUrl(url);
  33. dataSource.setUsername(username);
  34. dataSource.setPassword(password);
  35. dataSource.setDriverClassName(driver);
  36. return dataSource;
  37. }
  38. // 配置SqlSessionFactory
  39. @Bean
  40. public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
  41. SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
  42. factoryBean.setDataSource(dataSource);
  43. factoryBean.setTypeAliasesPackage("space.anyi.entity");
  44. // 配置MyBatis设置
  45. org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
  46. configuration.setMapUnderscoreToCamelCase(true); // 驼峰命名
  47. factoryBean.setConfiguration(configuration);
  48. return factoryBean;
  49. }
  50. // 配置Mapper扫描
  51. @Bean
  52. public MapperScannerConfigurer mapperScannerConfigurer() {
  53. MapperScannerConfigurer configurer = new MapperScannerConfigurer();
  54. configurer.setBasePackage("space.anyi");
  55. return configurer;
  56. }
  57. // 配置事务管理器
  58. @Bean
  59. public PlatformTransactionManager transactionManager(DataSource dataSource) {
  60. return new DataSourceTransactionManager(dataSource);
  61. }
  62. }