道
@Repository
public interface LoginDao extends JpaRepository<Login, Integer> {
Login findByLogin(String login);
}
验证
@Component
public class PasswordChangeValidator implements Validator {
private LoginDao loginDao;
@Override
public boolean supports(Class<?> aClass) {
return PasswordChange.class.equals(aClass);
}
@Override
public void validate(Object o, Errors errors) {
PasswordChange passwordChange = (PasswordChange) o;
**// There is a null pointer here because loginDao is null**
Login login = loginDao.findByLogin(passwordChange.getLoginKey());
}
public LoginDao getLoginDao() {
return loginDao;
}
@Autowired
public void setLoginDao(LoginDao loginDao) {
**// There is a debug point on the next line and it's hit on server startup and I can
// see the parameter us non-null**
this.loginDao = loginDao;
}
}
控制器
@Controller
@RequestMapping("api")
public class PasswordController {
@Autowired
PasswordService passwordService;
@InitBinder("passwordChange")
public void initBinder(WebDataBinder webDataBinder, WebRequest webRequest) {
webDataBinder.setValidator(new PasswordChangeValidator());
}
@RequestMapping(value = "/passwordChange", method = RequestMethod.POST)
public @ResponseBody PasswordInfo passwordInfo(@RequestBody @Valid PasswordChange passwordChange)
throws PasswordChangeException {
return passwordService.changePassword(passwordChange.getLoginKey(), passwordChange.getOldPassword(), passwordChange.getNewPassword());
}
}
我有上面列出的Dao。这个相同的dao bean被注入一个@Service注释类,但不会注入@Component注释的Validator类。好吧,不完全是在服务器启动时我可以看到调用setter方法,但是当我尝试在方法中使用此变量时,变量显示为null。
有人看到我的配置有问题吗?请注意,loginDao bean被注入服务类,因此Context配置很好。
答案 0 :(得分:3)
那就是你的问题
webDataBinder.setValidator(new PasswordChangeValidator());
Spring只能管理它创建的bean 。在这里,您正在创建实例。而是将您的bean注入@Controller
并使用它。
@Inject
private PasswordChangeValidator passwordChangeValidator;
...
webDataBinder.setValidator(passwordChangeValidator);