[英]Spring Boot: Autowired mapper fails
I am new to spring boot and mybatis.我是 spring boot 和 mybatis 的新手。 I create a repo which has structure:
我创建了一个具有结构的回购协议:
main
java
com
ssm
controller
UserController.java
mapper
UserMapper.java # can generated by mybatis generator
dao
UserDao.java # which extends interface UserMapper
model
User.java
service
UserService.java
UserServiceImpl.java
UserSpringBootApplication.java
resources
com
ssm
xml
UserMapper.xml
UserDao.xml
static
templates
application.properties
mybatis-config.xml
In file UserSpringBootApplication.java
, its content is在文件
UserSpringBootApplication.java
中,它的内容是
@SpringBootApplication
public class UserSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(UserSpringBootApplication.class, args);
}
}
In file UserDao.java
:在文件
UserDao.java
:
@Mapper
public interface UserDao extends UserMapper {
// example
@ResultMap("Record")
@Select("select * from UserTable")
List<User> getAllRecords();
}
In file UserMapper.java
:在文件
UserMapper.java
:
@Mapper
public interface UserMapper
In file application.properties
:在文件
application.properties
:
# database config
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test_db
spring.datasource.username=root
spring.datasource.password=xxxxxx
# mybatis
mybatis.config-location=classpath:mybatis-config.xml
In file UserServiceImpl.java
, I try to autowire UserDao.在文件
UserServiceImpl.java
中,我尝试自动装配 UserDao。 But when running application, it gives me error: Field UserDao in com.ssm.service.UserServiceImpl required a bean of type 'com.ssm.dao.UserDao' that could not be found.
但是在运行应用程序时,它给我错误:
Field UserDao in com.ssm.service.UserServiceImpl required a bean of type 'com.ssm.dao.UserDao' that could not be found.
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
// ...
}
application.properties
?application.properties
中设置有什么问题吗? Thanks a lot!多谢!
EDIT: This is only a solution for MapStruct
, the real solution is in the comments!编辑:这只是
MapStruct
的解决方案,真正的解决方案在评论中!
You should user the @Mapper
annotation like this:您应该像这样使用
@Mapper
注释:
@Mapper(componentModel = "spring")
From the javadoc:来自javadoc:
spring: the generated mapper is a Spring bean and can be retrieved via @Autowired
spring:生成的映射器是一个 Spring bean,可以通过@Autowired 检索
See: https://mapstruct.org/documentation/stable/api/org/mapstruct/Mapper.html请参阅: https://mapstruct.org/documentation/stable/api/org/mapstruct/Mapper.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.