【问题标题】:Loading Spring Properties in spring boot在 Spring Boot 中加载 Spring 属性
【发布时间】:2014-12-21 03:12:57
【问题描述】:

我正在尝试创建一个包含存储在 Spring Boot 中的属性文件中的值的类

到目前为止,我已经设置了属性“source.Ip”的 sample.properties 文件。

类如下:

@PropertySource({"classpath:sample.properties"})
@Configuration
@Component
public class PropertyLoader {

    @Value("${source.Ip}")
    private String sourceIp; 

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

    public String getSourceIP(){
        return sourceIp;
    }

}

属性文件直接在源文件夹 src/main/resources 下。

但是我得到一个:

java.lang.IllegalArgumentException: Could not resolve placeholder 'source.Ip' in string value "${source.Ip}"

至于我的主类,简单如下:

@Configuration
@EnableAutoConfiguration
public class AppStarter {

    public static void main(String args[]){
        System.out.println(SpringApplication.run(AppStarter.class, args).getBean(PropertyLoader.class).getSourceIP());

    }

    @Bean
    public PropertyLoader propertyLoader(){
        return new PropertyLoader();
    }
}

sample.properties 内容:

source.Ip=127.0.0.1

【问题讨论】:

    标签: java spring spring-mvc properties spring-boot


    【解决方案1】:

    为了使用来自PropertySource 的属性解析<bean> 定义或@Value 注释中的${...} 占位符,您必须注册PropertySourcesPlaceholderConfigurer。这在XML 中使用<context:property-placeholder> 时会自动发生,但在使用@Configuration 类时必须使用静态@Bean 方法显式注册。

    PropertySourcesPlaceholderConfigurer 的方法必须是静态的,因为 BeanFactoryPostProcessor (BFPP) 对象必须在容器生命周期的早期实例化,它们可能会干扰注释的处理,例如 @Autowired@Value@PostConstruct @Configuration 班级。

    将此添加到您的应用程序类应该可以解决问题:

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

    来自PropertySource documentation

    编辑

    你有没有尝试过

    1. PropertySourcesPlaceholderConfigurer 放入AppStarter 类中。
    2. PropertySource 注解移至AppStarter 类。
    3. 删除PropertyLoader上的Configuration注解。
    4. 移除使用 Bean 注解的 propertyLoader 方法。

    问题可能与PropertyLoader 是一个组件和一个配置类有关。

    【讨论】:

    • docs.spring.io/spring/docs/current/javadoc-api/org/… 这表明要使用从 3.1 开始的 PropertySourcesPlaceholderConfigurer。它在我的 PropertyLoader 中作为 bean 存在
    • 您是否尝试将 PropertySourcesPlaceholderConfigurer bean 放入 AppStarter 类中?
    • 移动 PropertySource 注释就足够了。
    • 如果您在答案中单独发布解决方案,我会将其标记为正确。
    • 我编辑我的 anwser。问题可能与 PropertyLoader 是一个组件和一个配置类这一事实有关。
    猜你喜欢
    • 1970-01-01
    • 2019-10-18
    • 2022-01-14
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2019-03-30
    • 2017-11-17
    相关资源
    最近更新 更多