Spring Boot :自动布线字段为无

8zzbczxx  于 2022-10-30  发布在  Spring
关注(0)|答案(1)|浏览(207)

我正在使用java spring创建一个电子日记应用程序,但是我遇到了一个小问题。我决定创建一个带有状态模式的角色系统。所以这个系统的逻辑应该看起来像这样:
1.在控制器中,接受请求后,创建context类的对象,context类的构造器根据用户角色得到具体的RoleClass(使用工厂)
1.在控制器中,我们调用要执行的上下文的方法
1.在上下文中,我们调用希望执行的角色的方法。
1.在角色类中,我们调用要执行的服务的方法。
但问题是,当我启动程序时,所有自动连接的服务字段都是空的。我在上下文类中添加了@Service注解,但没有用。我还尝试为上下文类创建bean,但没有任何变化。
这就是我的程序在启动后打印的内容:

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

下面是我的代码:
1.这是我的用户控制器

@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.这是我的角色工厂课程:

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.以下是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();
    }
}

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());
    }

有什么问题吗?如果你知道,请告诉我,我会非常感激的。

uurv41yg

uurv41yg1#

在此处使用构造函数自动布线:

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

我认为当spring自动连接带有私有字段的bean时,它首先通过空构造函数创建对象,然后通过反射填充字段(这是有意义的)。但是您在空构造函数中完成整个执行,所以此时字段不是自动连接的。

相关问题