【问题标题】:Spring Boot external configuration using @PropertySource annotation with file使用带有文件的 @PropertySource 注释的 Spring Boot 外部配置
【发布时间】:2018-11-12 06:14:08
【问题描述】:

我是 Spring Boot 新手,我想使用占位符 @PropertySource("file:${application_properties}") 从外部文件中读取属性,因此在配置文件中使用了前面提到和定义的注释 @Bean,

public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

但我得到了:

无法解析值“file:${application_properties}”中的占位符“application_properties”

我在tomcat server.xml/context.xml 中配置了applications_properties(不确定究竟是哪个文件)

注意:如果我使用@PropertySource("file:c:\filename"),它工作正常,但我想使用占位符并想在 tomcat 中定义该占位符(也想知道如何做到这一点)。您能否帮我使用@PropertySource 读取文件属性,这将读取tomcat 中定义的占位符。

谢谢

【问题讨论】:

  • 另一个更新是我只想使用文件而不是类路径
  • 你不能。在启动时替换占位符时仅考虑系统和环境变量。此外,您不需要 PropertySourcesPlaceholderConfigurer 的 bean,因为 Spring Boot 已经添加了那个。
  • 我们可以在任何 tomcat 文件中添加这些变量,以便当我们启动 tomcat 时它会加载所有这些系统和环境变量吗?(我知道我们可以从 eclipse 中作为参数传递,但任何添加这些变量的可能性归档,以便我们可以跟踪所有属性。

标签: spring spring-boot


【解决方案1】:

下面的类文件有两个属性文件 sql.properties & errorDefinition.properties 文件(/src/main/resource)

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@PropertySources({
        @PropertySource("classpath:sql.properties"),
        @PropertySource("classpath:errorDefinition.properties")
})
public class PropConfig {

    public PropConfig() {
        super();
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer PropertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

【讨论】:

  • 谢谢 Thirumal,但我不确定它与上述问题有什么关系?
  • 您问题的最佳解决方案是“spring-cloud-config-server”。只要它在 git 中,此微服务将从系统中的任何路径获取属性。 cloud.spring.io/spring-cloud-config
【解决方案2】:

你可以像下面这样使用。

@PropertySource("file:${app.home}/app.properties")

并在启动过程中通过,如下所示。

System.setProperty("app.home", "test");

java -jar -Dapp.home="/home/mkyon/test" example.jar

this

【讨论】:

  • Alien,感谢您的回答。我们有什么方法可以在 tomcate 中定义占位符属性并在 Spring Boot 中访问?
  • 你为什么要这么做?将所有文件保存在项目的资源文件夹中并由类路径使用..这是最简单的方法。
  • 因为我想根据环境更改文件位置,而该更改应该在应用程序外部。
  • ok..那么您可以将文件保存在 tomcat 中,并可以使用 String tomcatPath = System.getProperty("catalina.home"); 读取文件目录 = new File(tomcatPath + File.separator + "propertiesFileFolder");
  • 好的。什么要求是,假设我在 tomcat 中有一个 xml(context/server) 文件,我将在其中给出类似的上下文参数名称和值作为文件位置,以便我将使用该参数名称spring boot 配置类作为占位符。根据该解决方案的任何解决方案
猜你喜欢
  • 2018-04-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-17
  • 2017-08-18
  • 2015-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多