我正在尝试使用 Spring 和 Embedded Elastic 构建一个 REST API。我在尝试启动应用程序时收到 NoSuchBeanDefinitionException。
目前,我有这个用于连接弹性数据库:
@Configuration
public class EsConfig {
Node node;
@Bean
public Client es() {
node = nodeBuilder().local(true).node();
return node.client();
}
(Destructor)
}
在 Controller 中:
@RestController
public class Controller {
@Autowired
public Client elasticSearchClient;
...
}
但是当我启动它时,我得到了这个异常:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'controller': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public org.elasticsearch.client.Client package.Controller.elasticSearchClient;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [org.elasticsearch.client.Client] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
我尝试了一些不同的注释,但显然还差得很远。
最佳答案
没有 [some.Thing] 类型的限定 bean
意味着 spring 不知道适用于该接口(interface)的类。
原因可能是
- 具有
@Bean
方法的类不是@Configuration
类 - 类路径组件扫描程序未拾取
@Configuration
类。
Spring boot默认情况下只会扫描@SpringBootApplication
的子包层次结构。如果您想包含外部代码,可以通过 @ComponentScan
注释更改扫描行为。
@SpringBootApplication
@ComponentScan(basePackageClasses = {MyApp.class, SomeOtherClassInARootPackage.class})
public class MyApp {
...
将添加其他一些类的包(和子包),同时也扫描应用程序的包。
关于java - 使用 Spring Autowiring 嵌入式弹性件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33929310/