@Mapper和@MapperScan注解,xxx required a bean of type xxx that could not be found,

搭建springboot+mybatis+mysql+maven项目,从controller-service-dao,最后写mapper.xml,启动之后报错如下:

Field helloWorldDAO in com.example.demo.service.ServiceImpl.HelloWorldServiceImpl required a bean of type 'com.example.demo.DAO.HelloWorldDAO' that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.example.demo.DAO.HelloWorldDAO' in your configuration.

 报错基本的意思就是无法找到注入HelloWorldDAO这个bean,经过查找定位,可以用以下两种方法解决:

1:在HelloWorldDAO这个类上添加@Mapper注解,代码如下:

package com.example.demo.DAO;

import com.example.demo.entity.student;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
@Mapper
public interface HelloWorldDAO {
     List<student> query(String studentId) throws Exception;
}

2:在启动类上添加包@MapperScan注解,代码如下:

@MapperScan("com.example.demo.DAO")
public class DemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}

总结:在mapper接口上使用@Mapper注解,可以生成相应的接口实现类。如果接口类比较少的话,当然用@Mapper也是可以的。但是,我们平常在工作中,可能对应的接口比较多,这个时候用@Mapper注解就显得比较麻烦了。这个时候我们可以在启动类上加@MapperScan注解,@MapperScan("com.example.demo.DAO"),里面写对应接口的路径,这样我们只需要配置一次,在当前路径下的接口类中都可以使用了,这样是不是很方便呢。

知识就是要不断的学习,不断的复习,才会记忆的更加的深刻。加油,美好的风景一直在路上。

猜你喜欢

转载自blog.csdn.net/qq_36833673/article/details/106868914