Spring Boot中@Autowired无法注解

今天在使用Spring Boot main方法启动项目时遇到@Autowdired注解无法注入错误。
错误信息:

Parameter 0 of method setUserService in com.th.controller.SearchController required a bean of type 'com.th.service.UserService' that could not be found.


Action:

Consider defining a bean of type 'com.th.service.UserService' in your configuration.

SearchController代码类:

package com.th.controller;

import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.th.model.AjaxResponseBody;
import com.th.model.SearchCriteria;
import com.th.model.User;
import com.th.service.UserService;

@RestController
public class SearchController {

    UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/api/search")
    public ResponseEntity<?> getSearchResultViaAjax(@Valid @RequestBody SearchCriteria search, Errors errors) {

        AjaxResponseBody result = new AjaxResponseBody();

        if (errors.hasErrors()) {

            result.setMsg(
                    errors.getAllErrors().stream().map(x -> x.getDefaultMessage()).collect(Collectors.joining(",")));
            return ResponseEntity.badRequest().body(result);
        }

        List<User> users = userService.findByUserNameOrEmail(search.getUsername());
        if (users.isEmpty()) {
            result.setMsg("no user found!");
        } else {
            result.setMsg("success");
        }

        result.setResult(users);

        return ResponseEntity.ok(result);
    }
}

解决:
1、检查对应的service类,controller类有没有在类上注解@Service@RestController
2、检查main启动类是否在service层,dao层的上一级,否则程序扫描不到

猜你喜欢

转载自blog.csdn.net/ththcc/article/details/81626226
今日推荐