生產(chǎn)環(huán)境
- SpringBoot
- Hibernate
問題描述
在service層的LoginService中我使用@Resource注入了SpringBoot的UserRepository接口,在controller層的LoginController中調(diào)用了LoginService中的CheckPassword靜態(tài)方法竭望,運(yùn)行過程出現(xiàn)了UserRepositoy注入失敗的問題硬爆,經(jīng)過查找資料發(fā)現(xiàn)@Resource不能用于注入靜態(tài)變量鱼鼓,所以我去掉了靜態(tài)變量并在LoginController中new了一個(gè)LoginService對(duì)象苍在,還是注入失敗盖腕,經(jīng)過查找資料發(fā)現(xiàn)存在@Resource的類不能使用new(自己注入依賴)
解決方案
將LoginService也改為@Resource注入鲸湃,需要在LoginService類前加上@Component注解,因?yàn)锧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("密碼錯(cuò)誤");
}
return user;
} catch (NullPointerException e) {
System.out.println("無法登錄华弓,數(shù)據(jù)庫中不存在該用戶");
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<LoginData> baseResponse = new BaseResponse<>();
baseResponse.setData(loginData);
return (baseResponse);
} catch (DemoException e) {
BaseResponse<String> baseResponse = new BaseResponse<>();
baseResponse.setStatus("error");
baseResponse.setData(e.getMessage());
return baseResponse;
}
}
}