【发布时间】:2019-08-28 19:47:48
【问题描述】:
我有一个标准的 springboot 网络应用程序。我想加载不在类路径中的属性文件。 application.properties 在类路径中并且被正确读取。
我在构建 jar 时没有问题。我只是将 .properties 放在 jar 旁边,它就可以工作了。但是当我打包一个战争时,我无法让应用程序读取属性文件。
【问题讨论】:
标签: spring spring-boot tomcat war
我有一个标准的 springboot 网络应用程序。我想加载不在类路径中的属性文件。 application.properties 在类路径中并且被正确读取。
我在构建 jar 时没有问题。我只是将 .properties 放在 jar 旁边,它就可以工作了。但是当我打包一个战争时,我无法让应用程序读取属性文件。
【问题讨论】:
标签: spring spring-boot tomcat war
您将属性文件与 application.properties 文件并行放置,并将其加载到这样的类中:
@PropertySource("classpath:foo.properties")
public class My class {
@Value( "${some.property}" )
String myProp;
}
【讨论】:
您可以使用ClassPathResource。给定加载资源的类。
这是给你的示例代码
ClassPathResource resource = new ClassPathResource("/application/context/blabla.yml");
InputStream inputStream = resource.getInputStream();
File file = resource.getFile();
// using inputStream or file
【讨论】:
您可以使用 spring 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
【讨论】: