温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring Boot中MyBatis依赖注入方式

发布时间:2024-09-11 11:33:29 来源:亿速云 阅读:84 作者:小樊 栏目:编程语言

在 Spring Boot 中,我们可以使用以下两种方式将 MyBatis 的依赖注入到项目中:

  1. 使用 Starter 自动配置:

在项目的 pom.xml 文件中添加 MyBatis 和 MyBatis-Spring-Boot-Starter 的依赖:

   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>2.1.4</version>
</dependency>

然后在 application.propertiesapplication.yml 文件中配置 MyBatis 的相关信息,例如:

# application.properties
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity

或者

# application.yml
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.demo.entity

这样,Spring Boot 会自动配置 MyBatis,并将其注入到项目中。

  1. 手动配置:

在项目的 pom.xml 文件中添加 MyBatis 和 MyBatis-Spring 的依赖:

   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.5.6</version>
</dependency><dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis-spring</artifactId>
   <version>2.0.6</version>
</dependency>

然后创建一个配置类,例如 MyBatisConfig.java,并在其中配置 MyBatis 的相关信息:

@Configuration
@MapperScan("com.example.demo.mapper")
public class MyBatisConfig {

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        return factoryBean.getObject();
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage("com.example.demo.mapper");
        return configurer;
    }
}

这样,MyBatis 就会被手动配置并注入到项目中。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI