繁体   English   中英

无法在Spring Boot应用程序的其他包中加载bean

[英]Cannot load bean in different package in Spring Boot application

我正在尝试从Spring引导应用程序上的其他包中加载bean。 这是我的主类,位于com.xyz.app包中:

Application.java

@SpringBootApplication(scanBasePackages = { "com.xyz.app.repository" })
public class Application extends SpringBootServletInitializer {

 @Override
 protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(Application.class);
 }

 public static void main(String[] args) {
    ConfigurableApplicationContext context = 
                            SpringApplication.run(Application.class, args);

    context.getBean(MyInterfaceRepository.class).loadData();
 }

接口MyInterfaceRepository.java位于com.xyz.app.repository包内,并且定义如下:

@RepositoryRestResource(collectionResourceRel = "aas", path = "aas")
public interface MyInterfaceRepository extends MongoRepository<MyClass, Long>, 
                                                 MyCustomInterface {
  ...
}

然后,我还有一个MyInterfaceRepositoryImpl.java ,它位于com.xyz.app.repository中 ,为MyCustomInterface.java提供一个实现,它也位于com.xyz.app.repository中

启动我的应用程序,我得到以下信息:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xyz.app.repository.MyInterfaceRepository] is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:372)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:332)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1066)
    at com.xyz.app.Application.main(Application.java:60)

我已经检查过了,实际上,是否将MyInterfaceRepository.javaMyInterfaceRepositoryImpl.javaApplication.javacom.xyz.app放在同一包中,是否可以使用。

似乎Spring不能从与Application.java所在的包不同的包中加载Bean。

另外,我尝试用以下命令替换@SpringBootApplication

@Configuration
@EnableAutoConfiguration
@ComponentScan({"com.xyz.app.repository"})

同样的问题。。

如果您使用的是Spring mongodb,则无需使用批注: @RepositoryRestResource(collectionResourceRel = "aas", path = "aas")

您还可以在MyInterfaceRepository使用@Autowired

在您的应用程序类/主类上,添加@EnableMongoRepositories。 您应该具有以下内容:

@SpringBootApplication(scanBasePackages = {"com.xyz.app"})
@EnableMongoRepositories(basePackages = {"com.xyz.app.repository"}, repositoryBaseClass = MyInterfaceRepositoryImpl.class)
public class Application extends SpringBootServletInitializer {
    ...
}

有关注释的更多详细信息,请参见EnableMongoRepositories

暂无
暂无

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

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