首页 > 解决方案 > Spring-boot:找不到bean

问题描述

我是 Spring Boot 新手,我正在为基本实践编写 CRUD 操作,这是我的代码。

演示应用程序.java:

 package com.example.controller;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;

 @SpringBootApplication
  public class DemoApplication {

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

}

用户.java

   package com.example.model;

  public class User {
   String userName;
  String password;

public String getUserName() {
    return this.userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

}

用户服务.java:

 package com.example.services;
 import com.example.model.User;
 import org.springframework.stereotype.Repository;
 import org.springframework.stereotype.Service;

 @Repository
 public interface UserServices {
     public String loginService(User user);
 }

UserServiceImplementatioin.java:

package com.example.serviceimplementation;
import com.example.model.User;
import com.example.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImplementation implements UserServices {
    public String loginService(User user) {
     if(user.getUserName().equals("demouser") && user.getPassword().equals("demopass")) {
        return "Login successfully";
     }
    return "Invalid Username and password";

    }
 }

服务控制器.java:

  package com.example.controller;
  import com.example.services.UserServices;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Service;
  import org.springframework.web.bind.annotation.*;
  import com.example.model.User;

 @RestController
 @RequestMapping(value="/askmeanything")
  public class ServiceController {
  @Autowired
  private UserServices userServices;

  public UserServices getUserServices() {
    return userServices;
  }

  public void setUserServices(UserServices userServices) {
    this.userServices = userServices;
  }

 @CrossOrigin(origins = "*")
 @RequestMapping(value = "/login", method = RequestMethod.POST)
  public String getMsg(@RequestBody User user) throws  Exception {
    return userServices.loginService(user);
  }
}

上面的代码给了我错误 com.example.controller.ServiceController 中的字段 userServices 需要找不到类型为“com.example.services.UserServices”的 bean。

标签: javaspring-boot

解决方案


这是因为你DemoApplication是在他下面的包中定义的com.example.controller。因此,默认情况下,Spring 只会扫描该包和它的来源。例如com.example.controller.something。它不会扫描父包。

要么将您DemoApplication的包移至父包,要么必须为组件扫描指定正确的包。

@SpringBootApplication(scanBasePackages={"com.example"})

我建议将类移动到父包,让 spring boot 发挥作用。


推荐阅读