Tho*_* Oo 1 spring spring-boot
我将多个@Bean方法放在一个@SpringBootApplication类中以创建所需的bean。它们全部运行,除了一个。该Bean方法永远不会运行,因此,相应的类(被标注为Service)会抱怨异常: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;
}
}
Run Code Online (Sandbox Code Playgroud)
删除@Service注释。
你是混合手册bean创建与@Bean和类注释(@Service,@Controller,@Component等)的组件扫描。这导致重复的实例。
否则,如果要离开@Services而不是手动创建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;
}
Run Code Online (Sandbox Code Playgroud)
完成此操作后,建议您阅读有关外部化配置的信息,以便您可以在application.properties文件中定义这些字符串,并可以从容易地对其进行更改中受益,而无需重新编译应用程序。
| 归档时间: |
|
| 查看次数: |
1318 次 |
| 最近记录: |