简体   繁体   中英

Methods in service layer are recognized as static

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM