Methods in service layer are recognized as static

Viewed 39

I built a Spring Boot application and added several methods in the service layer. Then I autowired their class into the Controller. IDEA shows an error that

Non-static method 'findAll()' cannot be referenced from a static context.

@Autowired
public UserMapper Usermanager;


public List<UserEntity> findAll() {
    List<UserEntity> list = Usermanager.findALL();
    return list;
}

public List<UserEntity> findByName() {
    List<UserEntity> list = Usermanager.findByName();
    return list;
}

Static value is belong to the class instead of the object. For this reason if we use a static value NPE(NonePointerException) will happen.

1 Answers

The reason of this problem is that I invoked the class instead of instance object. All methods in class is static, they are absolutely not able to be invoke. There are codes in my controller.

@Autowired
    UserService userService;

    @Autowired
    UserMapper userMapper;

    //查找
    @GetMapping("/findall")
    public List<UserEntity> findAll() {
        //used to be:return UserService.findAll();
        return userService.findAll();
    }

    @GetMapping("/find/{name}")
    public List<UserEntity> findByName(@PathVariable String name) {
        //used to be:return UserService.findByName();
        return userService.findByName();
    }
Related