【问题标题】:Spring @Repository @Document is not necessary?Spring @Repository @Document 不是必需的吗?
【发布时间】:2020-10-09 13:21:03
【问题描述】:

我有一个 Spring Boot 应用程序并连接到 Mongo DB。 我知道大多数文档或博客都说示例代码应该是这样的:

@Repository
public interface ProductRepository extends MongoRepository<Product, String> {

}

@Document
public class Product {
    private String id;
    private String name;
    private int price;
}

但我发现即使我删除了@Repository 和@Document 注释。该应用程序仍然可以正常启动。 Spring 仍然可以知道 ProductRepository 是 spring bean,也可以 CRUD Product 集合。

那么这些不需要添加@Repository 和@Document 吗?或者加不加有什么区别?

【问题讨论】:

    标签: java spring spring-boot spring-data-mongodb spring-annotations


    【解决方案1】:

    注解@Repository 将一个类注册为Spring bean,使其可自动装配。 Spring Data 不使用注解,而是通过扩展存储库类来提供功能,例如 JpaRepositoryMongoRepository

    【讨论】:

      【解决方案2】:

      不需要。

      Spring 可以找到它,因为您扩展了MongoRepository 接口,并在其类型中添加了Product

      @Repository 无论如何都很有用,例如,如果您创建自定义存储库。

      @Document 也是,如果您想指定自定义属性值,例如集合名称..

      【讨论】:

        猜你喜欢
        • 2022-12-12
        • 2011-06-06
        • 2022-01-06
        • 2021-12-22
        • 2011-12-24
        • 1970-01-01
        • 1970-01-01
        • 2021-07-04
        相关资源
        最近更新 更多