我在@Bean
类中放置了多个@SpringBootApplication
方法来创建所需的bean。除了一个,所有这些都运行。永远不会运行一个Bean方法,因此相应的类(注释为服务)会引发异常:org.springframework.beans.factory.NoSuchBeanDefinitionException
为什么一个Bean方法不会在同一个类中的其他方法运行时运行?
在调用consulService时,从不调用Application.java中的方法haProxyService。
// 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;
}
}
答案 0 :(得分:4)
删除@Service
注释。
您正在将手动Bean创建与@Bean
和类注释(@Service
,@Controller
,@Component
等)混合以进行组件扫描。这会导致重复的实例。
否则,如果您想离开@Service
而不想创建手动bean,则应使用@Bean
注释删除方法,并使用@Value
注释注入字符串值。
示例:
// Application.java:
@SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
}
// HAProxyService.java
@Service
public class HAProxyService extends BaseService {
@Value("/usr/local/bin/haproxy")
private String executablePath;
@Value("/root/Documents/consulProto/haproxy.conf")
private String confFilePath;
}
// ConsulService.java
@Service
public class ConsulService extends BaseService {
@Value("/usr/local/bin/com.thomas.Oo.consul.consul")
private String executablePath;
@Value("/root/Documents/consulProto/web.json")
private String confFilePath;
}
执行此操作后,我建议您阅读externalizing your configuration,以便在application.properties
文件中定义这些字符串,并且无需重新编译应用程序即可轻松更改这些字符串。