我是Spring Boot的新手,我正在为基本实践编写CRUD操作,这是我的代码。
DemoApplication.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);
}
}
User.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;
}
}
UserServices.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";
}
}
ServiceController.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。
答案 0 :(得分:3)
这是因为您的DemoApplication
是在以下软件包com.example.controller
中定义的。因此,默认情况下,Spring将仅扫描该程序包及其外观。例如。 com.example.controller.something
。它不会在父程序包中扫描。
要么将DemoApplication
移动到父程序包,要么必须为组件扫描指定正确的程序包。
@SpringBootApplication(scanBasePackages={"com.example"})
我建议将类移到父包,然后让spring boot发挥作用。