@Resource注入失败

生产环境

  • SpringBoot
  • Hibernate

问题描述

在service层的LoginService中我使用@Resource注入了SpringBoot的UserRepository接口,在controller层的LoginController中调用了LoginService中的CheckPassword静态方法,运行过程出现了UserRepositoy注入失败的问题,经过查找资料发现@Resource不能用于注入静态变量,所以我去掉了静态变量并在LoginController中new了一个LoginService对象,还是注入失败,经过查找资料发现存在@Resource的类不能使用new(自己注入依赖)

解决方案

将LoginService也改为@Resource注入,需要在LoginService类前加上@Component注解,因为@Resource是通过name来查找需要注入的Bean的

最终代码

  • com.example.demo.service.LoginService
@Component("LoginService")
public class LoginService {
    @Resource
    private UserRepository userRepository;

    public void checkValidation(String username, String password) throws DemoException{
        if (username == null || username.isEmpty()) {
            throw new DemoException("用户名不能为空");
        } else if (password == null || password.isEmpty()) {
            throw new DemoException("密码不能为空");
        }
    }


    public User checkPassword(String username, String password) throws DemoException {
       try {
           System.out.println(username);
           System.out.println(userRepository);
           User user = userRepository.findByUsername(username);
           if (!password.equals(user.getPassword())) {
               throw new DemoException("密码错误");
           }
           return user;
       } catch (NullPointerException e) {
           System.out.println("无法登录,数据库中不存在该用户");
           throw new DemoException(("用户不存在"));
       }
    }
}
  • com.example.demo.controller.LoginController
@RestController
@RequestMapping("/login")
public class LoginController {

    @Resource
    LoginService loginService;

    @PostMapping
    public BaseResponse Login(@RequestBody LoginRequest loginRequest) {


        try {
            String username = loginRequest.getUsername();
            String password = loginRequest.getPassword();
            loginService.checkValidation(username, password);
            User user = loginService.checkPassword(username, password);
            LoginData loginData = new LoginData();
            loginData.setId(user.getId());
            loginData.setType(user.getId());
            BaseResponse baseResponse = new BaseResponse<>();
            baseResponse.setData(loginData);
            return (baseResponse);
        } catch (DemoException e) {
            BaseResponse baseResponse = new BaseResponse<>();
            baseResponse.setStatus("error");
            baseResponse.setData(e.getMessage());
            return baseResponse;
        }

    }

}

你可能感兴趣的:(@Resource注入失败)