gpt4 book ai didi

Spring初始化在项目外完成

转载 作者:行者123 更新时间:2023-12-04 14:55:26 25 4
gpt4 key购买 nike

我有一个 java spring 项目。我看到初始化 spring 项目的一种方法是在 main 方法中使用此代码。

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(Config.class);
ctx.scan("com.example.db.app");
ctx.refresh();

是否可以将它保留在主要方法之外,然后将这个项目制作成一个 jar。将它作为依赖项添加到其他项目的 pom.xml 中,并从那里调用初始化 spring Artifact 的方法。

我试过了。我收到一个错误。

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itemInformationRepositoryService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.example.db.app.service.ItemInformationRepositoryService.setItemInformationRepositoryService(com.example.db.app.repository.ItemInformationRepository); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.db.app.repository.ItemInformationRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

最佳答案

异常消息指出:

No qualifying bean of type [com.example.db.app.repository.ItemInformationRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

这意味着 com.example.db.app.repository.ItemInformationRepository 类不在 Spring 上下文中。也许您希望 Spring 发现此类是因为您指示 Spring 扫描 com.example.db.app?根据 AnnotationConfigApplicationContext.scan() 的 Javadocs ...

Perform a scan within the specified base packages.

@param basePackages the packages to check for annotated classes

因此,为了让 Spring 发现 com.example.db.app.repository.ItemInformationRepository,您必须:

  • org.springframework.stereotype.Component注释它,以便它被scan()发现
  • 以与注册 Config.class 相同的方式注册它,例如ctx.register(ItemInformationRepository.class);

关于Spring初始化在项目外完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45803887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com