繁体   English   中英

在Spring Boot中加载Spring属性

[英]Loading Spring Properties in 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

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

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

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

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

来自PropertySource文档

编辑

你有没有尝试

  1. PropertySourcesPlaceholderConfigurer放在AppStarter类中。
  2. PropertySource批注移动到AppStarter类。
  3. 删除PropertyLoader上的Configuration批注。
  4. 删除用Bean注释的propertyLoader方法。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM