【发布时间】:2021-04-15 09:43:02
【问题描述】:
我是 Spring Boot 框架的新手。
我正在尝试开发一个服务器来响应客户的请求,通过 REST API 架构在我的 mongodb 存储库中提供代表书籍模型的 json 文件。
这就是我所拥有的:
图书
public class Book implements Serializable {
@Id
private String id;
private String name;
private String author;
public Book(String id, String name, String author) {
this.id = id;
this.name = name;
this.author = author;
}
// Getters and setters here
}
BookController
@RestController
@RequestMapping(path = "api/v1/books")
public class BookController {
private final BookService bookService;
@Autowired
public BookController(BookService bookService) {
this.bookService = bookService;
}
@GetMapping
public List<Book> getBooks() {
return bookService.getBooks();
}
@GetMapping(params = "author")
public List<Book> getBooksByAuthor(@RequestParam String author) {
return bookService.getBooksByAuthor(author);
}
}
图书服务
@Service
public class BookService {
@Autowired // warning: field injection is not recommended
private BookRepository bookRepository;
@Autowired // warning: field injection is not recommended
private MongoTemplate mongoTemplate; // warning: could not autowire. No 'MongoTemplate' type found
public List<Book> getBooks() {
return bookRepository.findAll();
}
public List<Book> getBooksByAuthor(String author) {
Query query = new Query();
query.addCriteria(Criteria.where("author").is(author));
return mongoTemplate.find(query, Book.class);
}
}
书库
@Repository
public interface BookRepository extends MongoRepository<Book, String> {
}
即使 localhost:8080/api/v1/books?author=SOMETHING 工作正常,IntelliJ 也会警告我 @Autowired private BookRepository bookRepository;
不推荐现场注入
和@Autowired private MongoTemplate mongoTemplate;
不推荐现场注入
无法自动装配。未找到“MongoTemplate”类型
我有这些问题:
-
此服务器应用程序的结构是否正确?我的意思是,每个组件(控制器、服务和存储库)之间的交互
-
如何克服
BookService中的这两个警告? -
您是否会对我的代码进行任何更改?例如命名约定、自动装配等? (我的意思是一些建议)。比如我会搬家
查询 query = new Query(); query.addCriteria(Criteria.where("author").is(author)); return mongoTemplate.find(query, Book.class);
声明为BookRepository
【问题讨论】:
-
你可以试试
MongoOperations(接口MongoTemplate实现)。 -
@prasad_ 它仍然会给我“无法自动装配。找不到 'MongoOperation' 类型”。
-
Intellij 看不到 Spring 的自动配置,因此看不到那些 bean。所以 intellij 是错误的,你的应用程序可以正常工作。关于字段注入,只需删除
@Autowired,将字段设置为 final 并创建适当的构造函数。此外,BookRepository上的@Repository删除也没用。 -
@M.Deinum 即使我在构造函数中执行 this.mongoTemplate = mongoTemplate,它也会给我同样的警告(无法自动装配)
-
正确,因为正如我之前提到的,Intellij 不知道 Spring Boot 自动配置,因此认为 bean 不会存在。
标签: java spring mongodb spring-boot