如何在打包为战争的spring启动应用程序中加载其他属性文件?

问题描述 投票:0回答:3

我有一个标准的springboot网络应用程序。我想加载不在类路径中的属性文件。 application.properties位于类路径中,正在被正确读取。

我正在建造一个罐子时没有问题。我只是把.properties放在罐子旁边然后就可以了。但是当我打包战争时,我无法让应用程序读取属性文件。

spring spring-boot tomcat war
3个回答
0
投票

您将属性文件与application.properties文件并行,并将其加载到类如下所示的类中:

@PropertySource("classpath:foo.properties")
public class My class {

@Value( "${some.property}" )
String myProp;

}

0
投票

你可以使用ClassPathResource。给定加载资源的类。

这是您的示例代码

ClassPathResource resource = new ClassPathResource("/application/context/blabla.yml");
InputStream inputStream = resource.getInputStream();
File file = resource.getFile();

// using inputStream or file

ClassPathResource


0
投票

您可以使用弹簧application.properties来获得弹簧轮廓,并使用弹簧轮廓为每个环境定义单独的属性。您甚至可以将弹簧轮廓分离到不同的文件,如appication-dev.properties等,这样您就可以将每个弹簧轮廓分开文件。

您可以使用@Configuration批注读取属性:

@Configuration
@EnableConfigurationProperties(TestProperties.class)
public class MySampleConfiguration {
} 

这里,TestProperties.class用于映射属性文件或yaml中的值。详细参考:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

© www.soinside.com 2019 - 2024. All rights reserved.