我试图用Spring和Embedded Elastic构建一个rest api。我在尝试启动应用程序时遇到了NoSuchBeanDefinitionException。
目前,我有这个用于连接弹性db:
@Configuration
public class EsConfig {
Node node;
@Bean
public Client es() {
node = nodeBuilder().local(true).node();
return node.client();
}
(Destructor)
}
并在控制器中:
@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)}
我尝试了一些不同的注释,但我很快就离开了。
答案 0 :(得分:1)
No qualifying bean of type [some.Thing]
表示spring不知道任何适用于此接口的类。
原因可能是
@Bean
方法的类不是@Configuration
类@Configuration
类。默认情况下,Spring启动只会扫描@SpringBootApplication
的子包层次结构。如果要包含其外的代码,可以通过@ComponentScan
注释更改扫描行为。
@SpringBootApplication
@ComponentScan(basePackageClasses = {MyApp.class, SomeOtherClassInARootPackage.class})
public class MyApp {
...
会添加其他类的包(和子包),同时保持应用程序包的扫描。