【问题标题】:Spring won't inject a JPARepository beanSpring 不会注入 JPARepository bean
【发布时间】:2014-03-28 15:46:14
【问题描述】:

@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 bean 被注入到 @Service 注解的类中,但没有注入到 @Component 注解的 Validator 类中。好吧,不完全是在服务器启动时,我可以看到 setter 方法被调用,但是当我尝试在方法中使用此变量时,该变量显示为 null。

有人发现我的配置有问题吗?请注意,loginDao bean 被注入到服务类中,因此 Context 配置是好的。

【问题讨论】:

  • 你想在哪里使用PasswordChangeValidator? Spring 无法注入 null。您可能正在自己创建实例。
  • 在控制器方法内部使用@Valid注解。我正在使用控制器内的@InitBinder 注释绑定验证器。我并不是说它在注入 null,只是 loginDao 在不应该注入的情况下为 null。
  • @InitBinder向我们展示该代码。
  • 添加了控制器代码。

标签: java spring spring-mvc


【解决方案1】:

那是你的问题

webDataBinder.setValidator(new PasswordChangeValidator());

Spring 只能管理它创建的 bean。在这里,您正在创建实例。而是将您的 bean 注入 @Controller 并使用它。

@Inject
private PasswordChangeValidator passwordChangeValidator;
...
webDataBinder.setValidator(passwordChangeValidator);

【讨论】:

  • 宾果游戏,就在眼前,感谢您的帮助。
猜你喜欢
  • 2015-03-04
  • 2012-01-01
  • 1970-01-01
  • 2011-07-16
  • 2014-10-06
  • 1970-01-01
  • 2017-08-31
  • 1970-01-01
  • 2019-08-11
相关资源
最近更新 更多