java - 在 Spring Boot 中加载 Spring 属性

标签 java spring spring-mvc properties spring-boot

我正在尝试创建一个包含存储在 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

最佳答案

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

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

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

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

来自PropertySource documentation .

编辑

你有没有尝试过

  1. 输入 PropertySourcesPlaceholderConfigurerAppStarter类。
  2. 移动PropertySource AppStarter 的注释类。
  3. 删除 Configuration PropertyLoader 上的注释.
  4. 删除使用Bean注释的propertyLoader方法。

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

关于java - 在 Spring Boot 中加载 Spring 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26562190/

相关文章:

java - 是否可以使用广播接收器在设备主屏幕上显示警报对话框,而不是在我们的应用程序主要 Activity 上显示警报对话框?

java - Spring MVC。加载上下文时无法识别 RequestMapping 注释名称属性

java - 如何在线程中创建一个TextView?

java - Spring NON MVC 项目配置 - 最佳实践

java - 如何测试 Spring RESTful MVC Controller 方法?

Spring:组件中的 Autowiring 服务为空

java - 我应该在生产中使用什么 tomcat native 库?

spring - @RequestParam,名称与值属性

java - 高效更新 DelayQueue 中的元素

java - 卡夫卡连接。如何为连接器启用 jmx 指标