在封裝fastdfs客戶端的時候,發(fā)現(xiàn)在本地運行能夠獲取到配置文件的路徑
/**
* 初始化客戶端
* ClientGlobal.init(filePath) 讀取并初始化客戶端
*/
static {
try {
String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
logger.info("初始化filePath{}",filePath);
ClientGlobal.init(filePath);
} catch (Exception e) {
logger.error("初始化FastDFS失敗", e.getMessage());
}
}
結(jié)果:

打包前
打成jar包之后就無法獲取文件了,原因是resource目錄會打包到j(luò)ar包的目錄,我們上傳文件到服務(wù)器,肯定不會讀取這個絕對路徑,而是讀取打包后resource下的文件,所以絕對路徑就行不通了,找不到文件就是情理之中的了。
查閱資料后發(fā)現(xiàn),打包后是一個jar包,無法直接讀取jar包中的文件,讀取只能通過類加載器讀取。類加載器讀取jar包中編譯后的class文件,自然就能讀取到我們想要的conf文件。解壓jar包后查看目錄結(jié)構(gòu),發(fā)現(xiàn)yml和conf都在class下:

image.png
然后我們可以根據(jù)yml讀取的原理來讀取這個配置文件即可
翻閱springboot的run實現(xiàn)源碼,找到讀取方式

image.png
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
DefaultBootstrapContext bootstrapContext = createBootstrapContext();
ConfigurableApplicationContext context = null;
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting(bootstrapContext, this.mainApplicationClass);
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//看到這行,初始化環(huán)境
ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
configureIgnoreBeanInfo(environment);
/*注釋掉部分代碼*/
}
catch (Throwable ex) {
handleRunFailure(context, ex, listeners);
throw new IllegalStateException(ex);
}
return context;
}
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
DefaultBootstrapContext bootstrapContext, ApplicationArguments applicationArguments) {
// Create and configure the environment
ConfigurableEnvironment environment = getOrCreateEnvironment();
configureEnvironment(environment, applicationArguments.getSourceArgs());
ConfigurationPropertySources.attach(environment);
listeners.environmentPrepared(bootstrapContext, environment);
DefaultPropertiesPropertySource.moveToEnd(environment);
configureAdditionalProfiles(environment);
bindToSpringApplication(environment);
if (!this.isCustomEnvironment) {
environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
deduceEnvironmentClass());
}
ConfigurationPropertySources.attach(environment);
return environment;
}