前言
@Autowired
默认情况下要求依赖对象必须存在,而IDEA
对于Mybatis
接口的注入是无法理解的,被认为该对象是null
,虽然代码能正常运行,但有警告总归膈应
解决方案
为 @Autowired 注解设置 required = false
- 设置
required = false
后,不强制该对象在Spring
容器中,可以允许为null
@Autowired(required = false)
private UserMapper userMapper;
用@Resource替换@Autowired
@Resource
private UserMapper userMapper;
在Mapper接口上添加@Repository注解
@Repository
public interface UserMapper extends Mapper<User> {
}
使用Lombok - @RequiredArgsConstructor注解
-
@RequiredArgsConstructor
会为final
的属性产生一个构造函数。
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserController {
private final UserMapper userMapper;
}
- 生成的源码如下:
@RestController
@RequestMapping({"/user"})
public class UserController {
@Autowired
private final UserMapper userMapper;
@Autowired
public UserController(final UserMapper userMapper) {
this.userMapper = userMapper;
}
}