所以我这几周一直在学习 Spring,一直在学习这个教程
一切都很好,直到我尝试将它集成到 mongodb。所以我按照这个教程。
但我的做法部分仍在使用第一个。所以我的项目目录结构是这样的。
src/
├── main/
│ └── java/
| ├── model/
| | └── User.java
| ├── rest/
| | ├── Application.java
| | ├── IndexController.java
| | └── UsersController.java
| └── service/
| └── UserService.java
└── resources/
└── application.properties
这是我的 模型/User.java 文件
package main.java.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="user")
public class User {
private int age;
private String country;
@Id
private String id;
private String name;
public User() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
这是我的 rest/UsersController.java 文件
package main.java.rest;
import java.util.List;
import main.java.service.UserService;
import main.java.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/users")
public class UsersController {
@Autowired
UserService userService;
@RequestMapping(method = RequestMethod.GET)
public List<User> getAllUsers() {
return userService.findAll();
}
}
这是我的 服务/UserService.java 文件
package main.java.service;
import java.util.List;
import main.java.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface UserService extends MongoRepository<User, String> {
public List<User> findAll();
}
我可以编译它们(我正在使用 gradle 进行编译,因为我正在遵循教程),但是当我运行 jar 文件时它抛出了这个错误。
应用程序无法启动
描述:
main.java.rest.UsersController 中的字段 userService 需要找不到类型为“main.java.service.UserService”的 bean。
行动:
考虑在您的配置中定义一个“main.java.service.UserService”类型的 bean。
不知道出了什么问题,我开始四处搜索,发现我需要包含 Beans.xml
文件并在其中注册 userService 。我这样做了,但它不起作用。我对此真的很陌生,所以我真的不知道发生了什么。
原文由 Eka Rudianto 发布,翻译遵循 CC BY-SA 4.0 许可协议
解决了。所以默认情况下,所有属于
@SpringBootApplication
声明的包都会被扫描。假设我的主类
ExampleApplication
具有@SpringBootApplication
声明是在com.example.something
com.example.applicant
中声明的,那么所有属于com.example.something
的组件都被扫描a---
不会被扫描。因此,根据这个 问题 有两种方法可以做到这一点。利用
这样,应用程序将扫描所有指定的组件,但我想如果规模越来越大怎么办?
所以我使用第二种方法,通过重组我的包并且它起作用了!现在我的包结构变成了这样。