gpt4 book ai didi

java - Spring 启动 : Autowired fields are none

转载 作者:行者123 更新时间:2023-12-05 02:26:00 25 4
gpt4 key购买 nike

我正在使用 java spring 创建一个电子日记应用程序,但我遇到了一个小问题。我决定创建具有状态模式的角色系统。所以这个系统的逻辑应该是这样的:

  1. 在 Controller 中,接受请求后,创建上下文类的对象。上下文类的构造函数根据用户角色获得具体的RoleClass。(它使用工厂)
  2. 在controller中我们调用我们想要执行的context的方法
  3. 在上下文中我们调用我们想要执行的角色的方法。
  4. 在角色类中我们调用我们想要执行的服务方法。

但是问题来了。当我启动程序时,所有 Autowiring 的服务领域都是空的。我给context类添加了@Service注解,但是没用。我还尝试为上下文类创建 bean,但没有任何改变。

这是我的程序在启动后打印的内容:

Caused by: java.lang.NullPointerException: Cannot invoke "com.diary.diary.service.UserService.getCurrentUser()" because "this.userService" is null

这是我的代码:

  1. 这是我的UserController:
@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);
}
}
}
  1. 这是我的 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();
}
}
  1. 这是我的 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();
}
}
}
  1. 角色的界面如下:
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();
}
}
  1. 这是 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());
}

那么可能是什么问题呢?如果您知道,请告诉我,我将不胜感激。

最佳答案

在这里使用构造函数 Autowiring :

public UserContext(@Autowire UserService userService) {
this.userService = userService;
userRole = RoleFactory.getUserRole(userService.getCurrentUser().getName());
}

我认为当 spring 使用私有(private)字段 Autowiring bean 时,它首先通过空构造函数创建对象,然后通过反射填充字段(这是有道理的)。但是您在空构造函数中执行了整个执行过程,因此此时该字段未 Autowiring 。

关于java - Spring 启动 : Autowired fields are none,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74089090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com