简体   繁体   English

Spring Boot Autowired对CrudRepository的支持

[英]Spring Boot Autowired support for CrudRepository

The Spring Boot CrudRepository interface seems to help me well once JPA entities are all set up. 一旦全部建立了JPA实体,Spring Boot CrudRepository接口似乎对我有很大帮助。 I have a situation where I'd like to create these CrudRepository instances as needed and not always based on @ Autowired annotation. 我遇到一种情况,我想根据需要创建这些CrudRepository实例,而不总是基于@ Autowired注释。 For example, in my use case, I have a GUI menu that will contain a list of domain (or reference) table names. 例如,在我的用例中,我有一个GUI菜单,其中将包含域(或引用)表名称的列表。 Depending on what the user selects, the program will then instantiate one of these CrudRepository implementations. 根据用户的选择,程序将实例化这些CrudRepository实现之一。

If I use @Autowired , then don't I have to end up with all possible known implementation in my code? 如果我使用@Autowired ,那么我不必在代码中以所有可能的已知实现结尾吗?

One hypothetical use case: 一个假设的用例:

public interface PublisherRepository extends CrudRepository<Publisher, Long> {
}

public interface AuthorRepository extends CrudRepository<Author, Long> {
}

(I just realized I still have to create these entities after all.) (我只是意识到我毕竟仍然必须创建这些实体。)

In the GUI menu, there will be "Publisher", "Author", etc., and I like to create the GUI maintenance components based on the above repository interfaces. 在GUI菜单中,将出现“发布者”,“作者”等,并且我想根据上述存储库界面创建GUI维护组件。 Would it be a good practice to put @Autowired as following or just create them dynamically? @Autowired放在后面还是仅动态创建它们是一个好习惯?

@Autowired
PublisherRepository publisherRepo;

@Autowired
AuthorRepository authorRepo;

If there were a way to create these repo instances, would you please teach me how that is done in Spring Boot? 如果有创建这些仓库实例的方法,请您教我在Spring Boot中是如何完成的? Thanks so much for the expertise sharing in advance! 非常感谢您提前分享专业知识!

Sincerely, 真诚的

Student_t 学生_t

Normally, beans are created eagerly, so @Autowiring not used beans is not a problem. 通常,bean会急切创建,因此@Autowiring未使用的bean不会有问题。 They will use memory and consume some startup time anyway. 他们将使用内存,并且会消耗一些启动时间。

If you really do not want to autowire, you may @Autowire org.springframework.beans.factory.BeanFactory and use getBean to get desired repository. 如果您真的不想自动连线,则可以@Autowire org.springframework.beans.factory.BeanFactory并使用getBean获取所需的存储库。 But this is terrible idea. 但这是一个可怕的想法。 This ties your @Service to Spring, and (in case your repository is not found) you will get late (during access) runtime exception, rather than startup-exception. 这会将您的@Service与Spring联系起来,并且(如果未找到您的存储库)您将(在访问期间)延迟(在访问期间)运行时异常,而不是启动异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM