首页 > 解决方案 > 使用带有文件的 @PropertySource 注释的 Spring Boot 外部配置

问题描述

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

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

但我得到:

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

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

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

谢谢

标签: springspring-boot

解决方案


下面的类文件有两个属性文件 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();
    }

}

推荐阅读