【发布时间】:2017-06-13 17:17:10
【问题描述】:
我将多个@Bean 方法放在@SpringBootApplication 类中以创建所需的bean。除了一个之外,所有这些都运行。那个 Bean 方法永远不会运行,因此,相应的类(被注释为服务)抱怨异常:org.springframework.beans.factory.NoSuchBeanDefinitionException
为什么一个 Bean 方法不会运行而同一个类中的其他方法运行?
Application.java 中的方法,haProxyService 永远不会被调用,而 consulService 会被调用。
// Application.java:
@SpringBootApplication
public class Application {
//Config for services
//Consul
String consulPath = "/usr/local/bin/com.thomas.Oo.consul.consul";
String consulConfPath = "/root/Documents/consulProto/web.json";
//HAProxy
String haproxyPath = "/usr/local/bin/haproxy";
String haproxyConfFilePath = "/root/Documents/consulProto/haproxy.conf";
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
@Bean
public ConsulService consulService(){
return new ConsulService(consulPath, consulConfPath);
}
@Bean
public HAProxyService haProxyService(){
return new HAProxyService(haproxyPath, haproxyConfFilePath);
}
}
// ConsulService.java
@Service
public class ConsulService extends BaseService {
String executablePath;
String confFilePath;
public ConsulService(String consulPath, String confFilePath) {
this.executablePath = consulPath;
this.confFilePath = confFilePath;
}
}
// HAProxyService.java
@Service
public class HAProxyService extends BaseService {
String executablePath;
String confFilePath;
public HAProxyService(String executablePath, String confFilePath) {
this.executablePath = executablePath;
this.confFilePath = confFilePath;
}
}
【问题讨论】:
-
当我从有问题的类中删除@Service 时,现在神奇地调用了 Bean 方法......这是怎么回事
-
你将不得不展示一些代码。没有人可以肯定地猜到这一点。
-
这里有一个要点:gist.github.com/thomas-oo/7d129f4a042fd87a8ed33f87a8dad396 Application.java 中的方法,haProxyService 永远不会被调用,而 consulService 会被调用。当我从 HAProxyService 中删除 @Service 时,bean 方法现在被调用.. 但我的问题仍未解决
-
您正在将手动 bean 创建与 @Bean 和类注释 (@Service) 混合用于组件扫描。这会导致重复的实例,可能会导致上述异常(因为找到了多个候选者)。
-
目前春季页面的文档已关闭,但您应该使用
@Value和@PropertySource(网络搜索关键字提示;)注入配置参数。
标签: spring spring-boot