由上一篇文章boot集成dubbo,使用@PropertySource引入配置文件,启动服务正常,但是无法将服务注册到zk上的问题,然后开始追根溯源;
1.spring boot 默认的加载配置文件的顺序是:
第一种是在jar包的同一目录下建一个config文件夹,然后把配置文件放到这个文件夹下;
第二种是直接把配置文件放到jar包的同级目录;
第三种在classpath下建一个config文件夹,然后把配置文件放进去;
第四种是在classpath下直接放配置文件。
这四种方式的优先级是从一到四一次降低的。(引用---月未明)
2.寻找@PropertySource注解引入的配置是在什么时候加载的,Spring框架开始解析PropertySource注解的方法位于ConfigurationClassParser类中,通过打断点,然后一级一级往上找,发现通过@PropertySource注解引入的配置文件是在创建上下文之后,而默认扫描的配置文件时再创建上下文之前,这个顺序问题导致中间再初始化一些bean的时候需要用到的参数没有注入进来,然后无法正常运行;由此找到原因;
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);//默认的加载配置文件是从这个地方开始
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
analyzers = new FailureAnalyzers(context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
refreshContext(context);//这个方法里面开始加载@PropertySource引入的配置文件
afterRefresh(context, applicationArguments);
listeners.finished(context, null);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
return context;
}
catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}
3.网上查询发现可以通过在默认的配置文件中添加参数sprng.config.location=xxxx
来指定外部配置文件,照做以后发现并没有实现;查找原因,网上说:spring.config.name 和 spring.config.location 是 environment property (环境属性)。在 application.yml (application.properties)中设置已经太迟了!;猜测是启动的时候这个值已经被覆盖了,优先级太低,然后用命令行启动,添加这个参数的话是可以生效的;例如
java -jar xxx.jar --spring.config.location=xxxx.properties
网友评论