在 Spring Boot 中使用注解进行 MyBatis 组件扫描和配置是相对简单的,你可以按照以下步骤进行操作:
- 添加依赖: 在
pom.xml
中添加 MyBatis 和 Spring Boot MyBatis 相关的依赖。
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version> <!-- 使用合适的版本号 -->
</dependency>
- 配置数据源和 MyBatis: 在
application.properties
或application.yml
中配置数据库连接信息和 MyBatis 相关配置。
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath*:mappers/*.xml
- 创建 MyBatis Mapper 接口: 创建包含 SQL 映射方法的 MyBatis Mapper 接口。
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE username = #{username}")
User findByUsername(String username);
}
- 配置扫描路径: 在 Spring Boot 主配置类上使用
@MapperScan
注解来配置 MyBatis Mapper 接口的扫描路径。
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.myapp.mappers") // 设置你的 Mapper 接口所在的包路径
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
在上述示例中,@MapperScan
注解指定了包路径 com.example.myapp.mappers
,这将扫描该路径下的所有 MyBatis Mapper 接口并注册到 Spring 容器中。
通过这些步骤,你就可以使用注解扫描的方式配置并使用 MyBatis 组件。确保将示例中的包路径、数据库连接信息等修改为你实际的配置。