错误:
Error creating bean with name ‘entity’: Injection of autowired
dependencies failed; nested exception is java.lang.IllegalArgumentException: key can’t be empty
现在我们在本地环境试试会不会出现同样的问题,代码如下:
相关配置:
bootstrap.properties配置文件
app.id=prometheus
apollo.meta=http://127.0.0.1:8080
apollo.bootstrap.enabled=true
apollo.bootstrap.namespaces=application,AlertConfig,AlertRules
env=dev
获取apollo 配置的bean
@Component
public class Entity implements Serializable {
@Value("${rulesPath}")
private String rulesPath;
public String getRulesPath() {
return rulesPath;
}
public void setRulesPath(String rulesPath) {
this.rulesPath = rulesPath;
}
}
@Autowired
private Entity entity;
@PostConstruct
private void printLog(){
System.out.println(entity.getRulesPath());
}
apollo.bootstrap.namespaces=AlertConfig,application,AlertRules
再换一下:
apollo.bootstrap.namespaces=AlertRules,AlertConfig,application
我们试了一下并没有出现同样的问题,那么问题到底出在了哪里?
从实验结果中发现,客户端获取到的值和Apollo 的 namespace有关,获取配置中第一个namespace中配置的数据,
那么问题到底出在哪?
我们尝试将@Value("${}")设置成这样
@Component
@EnableApolloConfig("AlertConfig")
public class Entity implements Serializable {
// @Value("${rulesPath}")
@Value("${}")
private String rulesPath;
public String getRulesPath() {
return rulesPath;
}
public void setRulesPath(String rulesPath) {
this.rulesPath = rulesPath;
}
似乎我们遗漏了一个细节:测试环境中我们的配置 value中有个特殊的东西 ${}
终于发现答案了,原来是@Value对 SpEL表达式进行了解析,先获取到了apollo配置中 rulesPath 对应的值,然后又对值里边的SpEL表达式进行了解析,所以出现了key can’t be empty的错误。
事情到这里就结束了吗?
现在我知道是哪里出了问题,我只需要将数据中的${}删除掉就好了,但是这个锅到底由谁来背呢?
修改配置的时候发现了这样一句话,很明显Apollo是不想为此背锅的,那么我只好忍痛割爱删除掉apollo的相关配置,
#app.id=prometheus
## set apollo meta server address, adjust to actual address if necessary
#apollo.meta=http://47.93.114.70:8080
#apollo.bootstrap.enabled=true
#apollo.bootstrap.namespaces=application,AlertRules,AlertConfig
#env=dev
@Slf4j
@SpringBootApplication
public class DemoApplication /*implements CommandLineRunner*/ {
@Component
public class Entity implements Serializable {
@Component
@ConfigurationProperties(value = "test")
public class config {
@Value("${key:123}")
private String key;
我们不用apollo了,直接在application.yml 配置文件里写个简单的参数行不行?
然后启动一下:
果然就没问题了,这个锅 apollo背定了
那么 如果我们在表达式里再写一些key还可以解析吗?
前方高能警告!!!!
O(∩_∩)O 发生了什么!它还可以解析SpEL里的key 但是如果是空的也是没有关系的
距离真相越来越近了
那么我们来看看是哪些骚操作导致这个错误
#app.id=prometheus #appid
## set apollo meta server address, adjust to actual address if necessary
#apollo.meta=http://47.93.114.70:8080 #ip
#apollo.bootstrap.enabled=true
#apollo.bootstrap.namespaces=application,AlertRules,AlertConfig
#env=dev #指定环境
由此看来 就是 apollo.bootstrap.enabled=true 的问题了,