在Controller中找不到必需的bean - 依赖项注入期间出错

时间:2017-07-04 18:48:25

标签: spring spring-boot

我有一个非常简单的弹簧启动应用程序,它具有简单的硬编码服务,但它不起作用,它给我Field userService in hello.UserController required a bean of type 'services.UserService' that could not be found错误。这是我的Application类,控制器和服务类。问题是当我尝试通过@Autowired注释注入userService时。我认为这已经在某处得到了回答,但我找不到相关的答案。请帮帮我或指出正确的答案。感谢

控制器

@RestController
@EnableAutoConfiguration
@RequestMapping("/api")

public class UserController {

public static Logger logger = LoggerFactory.getLogger(UserController.class);

@Autowired
UserService userService;

@RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
    List<User> users = userService.getAllUsers();
    if(users.isEmpty()) return new ResponseEntity(HttpStatus.NO_CONTENT);

    return new ResponseEntity<List<User>>(users,HttpStatus.OK);
}

}

应用

@SpringBootApplication(scanBasePackageClasses = 
{UserController.class})
@ComponentScan
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return args -> {

        System.out.println("Let's inspect the beans provided by Spring Boot:");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }

    };
 }

}

服务类

@Service

public class UserService {

List<User> users;

public UserService() {
    this.users = new ArrayList<>();
    users.add(new User(2, "Altaire", 23));
    users.add(new User(3, "Ezio", 21));
    users.add(new User(4, "Enzo", 23));
}

public User getUser(int id) {
    for (User user : users) {
        if (user.getId() == id) {
            return user;
        }
    }
    return null;
}

public List<User> getAllUsers() {
    return users;
}

public void addUser(User user) {
    users.add(user);
}

public void deleteUser(int id) {
    for (User user : users) {
        if (user.getId() == id) {
            users.remove(user);
        }
    }
}

public void updateUser(int id, String name, int age) {
    for (User user : users) {
        if (user.getId() == id) {
            user.setName(name);
            user.setAge(age);
        }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

在您拥有的应用程序类中

@SpringBootApplication(scanBasePackageClasses = 
{UserController.class})

您还应该添加服务类:

@SpringBootApplication(scanBasePackageClasses = 
{UserController.class,UserService.class})

请注意,您也可以使用scanBasePackages,而不仅仅是显式分类,例如

@SpringBootApplication(scanBasePackage = {"com.x.y"})