Spring学习笔记-Mybatis中Mapper和MapperScan注解&一些不是 mapper 的 interface 也会被处理成 mapper 而被创建成一个bean,启动报错
warning:
这篇文章距离上次修改已过421天,其中的内容可能已经有所变动。
在Spring框架中,MyBatis的Mapper接口可以通过@Mapper注解或者@MapperScan注解来进行扫描和注册。
@Mapper注解:直接在每个Mapper接口类上添加@Mapper注解,用于注册这个接口。
@Mapper
public interface UserMapper {
// ...
}@MapperScan注解:通过指定扫描的包路径,自动注册该包及其子包下所有的Mapper接口。
@Configuration
@MapperScan("com.example.mapper")
public class MyAppConfig {
// ...
}在使用@MapperScan时,可以指定多个包,用逗号或空格分隔。
有时候,你可能会遇到一些不是MyBatis的Mapper接口,但是你想要通过Spring自动注入。这时,可以使用@Component或者类似的注解(如@Service、@Repository)来注册这些接口。
@Component
public interface SomeService {
// ...
}使用@Component注解后,这个接口会被Spring容器扫描并注册为一个Bean,然后就可以在其他地方通过@Autowired或者@Inject注入使用。
评论已关闭