我正在使用 java spring 創建一個電子日記應用程式,但我遇到了一個小問題。我決定創建具有狀態模式的角色系統。所以這個系統的邏輯應該是這樣的:
- 在控制器中,接受請求后,它會創建背景關系類的物件。背景關系類的建構式根據用戶角色獲取具體的RoleClass。(它使用工廠)
- 在控制器中,我們呼叫我們想要執行的背景關系方法
- 在背景關系中,我們呼叫我們想要執行的角色方法。
- 在角色類中,我們呼叫我們想要執行的服務方法。
但這就是問題所在。當我啟動程式時,所有自動連接的服務領域都是空的。我@Service
在背景關系類中添加了注釋,但是沒有用。我還嘗試為背景關系類創建 bean,但沒有任何改變。
這就是我的程式在啟動后列印的內容:
Caused by: java.lang.NullPointerException: Cannot invoke "com.diary.diary.service.UserService.getCurrentUser()" because "this.userService" is null
所以這是我的代碼:
- 這是我的用戶控制器:
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private UserContext userContext;
@GetMapping("/marks")
public ResponseEntity<Object> getMarks() {
try {
return ResponseEntity.ok(userContext.getMarks());
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
}
}
}
- 這是我的UserContext類:
@Service
public class UserContext {
private UserRole userRole;
@Autowired
private UserService userService;
public UserContext() {
userRole = RoleFactory.getUserRole(userService.getCurrentUser().getName());
}
public List<HomeworkGetModel> getHomework() throws UserNotFoundException {
return userRole.getHomework();
}
public List<MarkGetModel> getMarks() throws UserNotFoundException {
return userRole.getMarks();
}
}
- 這是我的RoleFactory類:
public class RoleFactory {
private static UserRole userRole;
public static UserRole getUserRole(String roleName) {
if(userRole == null) {
buildUserRole(roleName);
}
return userRole;
}
private static void buildUserRole(String roleString) {
switch (roleString) {
case RoleNames.DEFAULT -> userRole = new DefaultRole();
case RoleNames.STUDENT -> userRole = new StudentRole();
case RoleNames.TEACHER -> userRole = new TeacherRole();
case RoleNames.ADMIN -> userRole = new AdminRole();
}
}
}
- 這是Role的界面:
public interface UserRole {
default UserGetModel getUser(long id) throws UserNotFoundException {
throw new NotImplementedException();
}
default List<UserGetModel> getAllUsers() {
throw new NotImplementedException();
}
default UserEntity updateUser(UserUpdateModel newUserData) throws UserNotFoundException {
throw new NotImplementedException();
}
default UserEntity deleteUser() throws UserNotFoundException {
throw new NotImplementedException();
}
default List<MarkGetModel> getMarks() throws UserNotFoundException {
throw new NotImplementedException();
}
default List<MarkGetModel> getMarksByDate(String date) throws UserNotFoundException, ParseException {
throw new NotImplementedException();
}
default List<MarkGetModel> getMarksBySubject(String subjectName) throws UserNotFoundException {
throw new NotImplementedException();
}
default List<MarkGetModel> getMarksByDateAndSubject(DateAndSubjectModel dateAndSubject) throws UserNotFoundException, ParseException {
throw new NotImplementedException();
}
default SubjectGetModel getSubject(long id) throws SubjectNotFoundException {
throw new NotImplementedException();
}
default SubjectGetModel getSubject(String name) throws SubjectNotFoundException {
throw new NotImplementedException();
}
default SchoolGetModel getSchoolById(long schoolId) throws SchoolNotFoundException {
throw new NotImplementedException();
}
default SchoolGetModel getSchoolByNumber(int schoolNumber) throws SchoolNotFoundException {
throw new NotImplementedException();
}
default List<SchoolGetModel> getSchools() {
throw new NotImplementedException();
}
default ClassGetModel getSchoolClass(ClassGetByNumberModel classData) throws com.diary.diary.exception.school_class.ClassNotFoundException, SchoolNotFoundException {
throw new NotImplementedException();
}
default List<ClassGetModel> getClasses() {
throw new NotImplementedException();
}
default List<HomeworkGetModel> getHomework() throws UserNotFoundException {
throw new NotImplementedException();
}
default List<HomeworkGetModel> getHomeworkByDate(String date) throws UserNotFoundException, ParseException {
throw new NotImplementedException();
}
default List<HomeworkGetModel> getHomeworkBySubject(String subjectName) {
throw new NotImplementedException();
}
default ClassEntity addClass(ClassAddModel classData) {
throw new NotImplementedException();
}
default ClassEntity addUserToClass(AdminAddUserToClassModel userAndClassModel) {
throw new NotImplementedException();
}
default ClassEntity deleteClass(long id) {
throw new NotImplementedException();
}
default UserEntity removeUserFromClass(AdminRemoveUserFromClassModel userClassModel) {
throw new NotImplementedException();
}
default SchoolEntity addSchool(SchoolAddModel schoolData) {
throw new NotImplementedException();
}
default SchoolEntity deleteSchool(long id) {
throw new NotImplementedException();
}
default UserEntity removeUserFromSchool(AdminRemoveUserFromSchoolModel userSchoolModel) {
throw new NotImplementedException();
}
default SubjectEntity addSubject(SubjectAddModel subjectData) {
throw new NotImplementedException();
}
default SubjectEntity updateSubject(SubjectUpdateModel newSubjectModel) {
throw new NotImplementedException();
}
default SubjectEntity deleteSubject(SubjectDeleteModel subjectDeleteData) {
throw new NotImplementedException();
}
default TimetableEntity addTimetable(TimetableAddModel timetableData) {
throw new NotImplementedException();
}
default TimetableEntity updateTimetable(TimeTableUpdateModel newTimetableData) {
throw new NotImplementedException();
}
default TimetableEntity deleteTimetable(long id) {
throw new NotImplementedException();
}
default ClassEntity addTimetableToClass(TimetableClassModel timetableClass) {
throw new NotImplementedException();
}
default ClassEntity deleteTimetableFromClass(long classId) {
throw new NotImplementedException();
}
}
- 這是UserService類:
@Service @Configurable
public class UserService implements UserDetailsService {
@Autowired
private UserRepository userRepo;
@Autowired
private RoleRepository roleRepo;
@Autowired
private MarkMethods markMethods;
private final BCryptPasswordEncoder bCryptPasswordEncoder
= new BCryptPasswordEncoder();
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserEntity user = userRepo.findByLogin(username);
if(user == null) {
throw new UsernameNotFoundException("user with such login not found");
}
SimpleGrantedAuthority userRole = new SimpleGrantedAuthority(user.getRole().toString());
return new User(Long.toString(user.getId()), user.getPassword(), List.of(userRole));
}
public List<MarkGetModel> getMarks() throws UserNotFoundException {
checkUserRoleOrThrow(RoleNames.ADMIN, getCurrentUser());
UserEntity student = getCurrentUser();
return convertToMarkGetModelList(student.getMarks());
}
那么可能是什么問題?如果你知道,請告訴我,我真的很感激。
uj5u.com熱心網友回復:
在此處使用建構式自動裝配:
public UserContext(@Autowire UserService userService) {
this.userService = userService;
userRole = RoleFactory.getUserRole(userService.getCurrentUser().getName());
}
我認為當spring自動裝配帶有私有欄位的bean時,它首先通過空建構式創建物件,然后通過反射填充欄位(這是有道理的)。但是您在空建構式中執行整個執行,因此此時該欄位未自動裝配。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/515361.html
標籤:爪哇春天弹簧靴爪哇豆