利用spring来配置文件路径

最近项目需要读取一些配置文件(excel),对于怎么取到文件路径,我想到了以下两种方法
1)this.getClass().getClassLoader().getResource("")
2)通过spring自带的org.springframework.core.io.Resource类
例子:


package com.pactera.platform.reqm.core.util;

import org.springframework.core.io.Resource;


/*
* 取得外部模板和标识文件路径的类
*
*/
public class FilePathGet {

// 表示文件路径
private Resource defineFile;

// 模板文件路径
private Resource excelFile;

public Resource getDefineFile() {
return defineFile;
}

public void setDefineFile(Resource defineFile) {
this.defineFile = defineFile;
}

public Resource getExcelFile() {
return excelFile;
}

public void setExcelFile(Resource excelFile) {
this.excelFile = excelFile;
}


}

配置文件
<bean id="defineFilePathGet" class="com.pactera.platform.reqm.core.util.FilePathGet">
<property name="defineFile" value="classpath:/com/pactera/platform/reqm/resources/modelDefine"></property>
<property name="excelFile" value="classpath:/com/pactera/platform/reqm/resources/modelExcel"></property>
</bean>

测试例子
[/code]

[code="java"]// 模板标识文件名编辑
StringBuilder fileName = new StringBuilder();

fileName.append(filePathGet.getDefineFile().getFile().getAbsolutePath());
### 如何在 Spring Boot 中指定自定义配置文件位置 在 Spring Boot 应用程序中,可以通过多种方式来指定自定义配置文件的位置。以下是几种常见的方式: #### 使用命令行参数 可以在启动应用程序时通过命令行参数传递配置文件的位置。例如: ```bash java -jar myapp.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties,file:./config/application.properties ``` 这会告诉 Spring Boot 从多个位置加载配置文件,并按照顺序覆盖相同的属性[^1]。 #### 修改 `application.properties` 或 `application.yml` 也可以直接在 `application.properties` 或者 `application.yml` 文件里指明其他外部配置文件的位置: 对于 properties 文件来说: ```properties spring.config.additional-location=file:///path/to/config/ ``` 而对于 yml 文件则是这样写: ```yaml spring: config: additional-location: file:///path/to/config/ ``` 这种方式允许开发者灵活地添加额外的配置源而无需改变原有的配置文件结构[^3]。 #### 利用环境变量 还可以利用操作系统的环境变量来设定配置文件路径,在 Linux/Unix 系统上可以这样做: ```bash export SPRING_CONFIG_LOCATION=/path/to/config/ ``` 而在 Windows 上则应使用 set 命令代替 export 。之后再运行 jar 包即可自动识别该目录下的配置文件[^2]。 以上方法均能有效地帮助用户更改默认情况下位于 classpath 下的应用程序配置文件的位置,从而满足不同场景下对资源配置的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值