我正在学习弹簧引导,并且正在做一个玩具项目-一个注册页面。
我有一个与UserMapper交互的MySQL接口,它看起来如下所示:
public interface UserMapper {
@Insert("INSERT INTO user (email, password, salt, confirmation_code, valid_time, isValid" +
"VALUES(#{email}, #{password}, #{salt}, #{confirmationCode}, #{validTime}, #{isValid})")
int insertUser(User user);在主类中,我添加了@MapperScan()注释,因此应该找到映射类的位置。
package com.example;
import...
@MapperScan("com.example.mapper")
@SpringBootApplication(scanBasePackages = "com.example")
public class SpringbootUserLoginApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootUserLoginApplication.class, args);
}
}然后,我在我的UserMapper类中调用UserService:
@Service
public class UserService {
private UserMapper userMapper;
public Map<String, Object> createAccount(User user){
// this is where the NullPointerException happens
int result = userMapper.insertUser(user);
Map<String, Object> resultMap = new HashMap<>();
if (result > 0) {
resultMap.put("code", 200);
resultMap.put("message", "Registration successful, activate account in your email.");
} else {
resultMap.put("code", 400);
resultMap.put("message", "Registration failed");
}
return resultMap;
}
}我得到的错误是java.lang.NullPointerException: Cannot invoke "com.example.mapper.UserMapper.insertUser(com.example.pojo.User)" because "this.userMapper" is null。
我还尝试在@Mapper()接口上添加UserMapper,但仍然得到了相同的错误。有谁知道我为什么会犯这个错误,以及如何修复它?任何帮助都将不胜感激!谢谢!
发布于 2022-05-26 03:09:19
将用户映射器自动转到UserService类中,如下所示:
@Autowired
private UserMapper userMapper;发布于 2022-05-26 03:36:44
或者你可以用这样的注射:
private final UserMapper userMapper;
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}https://stackoverflow.com/questions/72386085
复制相似问题