使用@PropertySource注释和文件进行Spring Boot外部配置

时间:2018-11-12 06:14:09

标签: spring spring-boot

我是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中定义的占位符。

谢谢

2 个答案:

答案 0 :(得分: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();
    }

}

答案 1 :(得分:0)

您可以按以下方式使用。

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

并在启动期间通过,如下所示。

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

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

请参阅this

相关问题