使用场景:当我们打包发布文件是需要将配置文件拿出来配置,这个时候就需要配置读取文件的位置
配置如下:
@Data
@Configuration
@ConfigurationProperties()
@PropertySource(value = {"classpath:/test.properties","file:./config/test.properties","file:./test.properties"},ignoreResourceNotFound = true)
public class TestConfig {
private String testFilePath;
}
classpath:/test.properties 读取jar包内的配置文件test.properties
file:./config/test.properties 读取jar包所处文件夹同级目录的config下配置文件test.properties
file:./test.properties 读取jar包所处文件夹同级配置文件test.properties
ignoreResourceNotFound指定是否忽略找不到的资源文件,默认是false,这意味着如果指定的资源文件不存在,会抛出异常;但在这里设置为true,表示即使找不到指定的资源文件也不会抛出异常,Spring会继续启动。
读取文件优先级根据配置路径从后向前读取配置
示例:
- TestConfig 配置
@Data
@Configuration
@ConfigurationProperties()
@PropertySource(value = {"classpath:/test.properties","file:./config/test.properties","file:./test.properties"},ignoreResourceNotFound = true)
public class TestConfig {
private String testFilePath;
}
- 启动类输出TestConfig 读取文件地址
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class TestApplication implements ApplicationListener<WebServerInitializedEvent> {
public static final Logger LOGGER = LoggerFactory.getLogger(TestApplication.class);
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
@Autowired
private TestConfig testConfig;
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
LOGGER.info("TestConfig 读取文件地址:"+ testConfig.getTestFilePath());
}
}
不同位置test.properties内容
config文件夹下test.properties内容
testFilePath=config
jar包同级目录test.properties内容
testFilePath=root
jar包内test.properties内容
testFilePath=jar
文件配置 jar包同级目录和config目录都存在test.properties
程序启动输出地址:root
文件配置 config目录下test.properties
程序启动输出地址:config
不进行外部文件配置
程序启动输出地址:jar