简体   繁体   中英

Loading Spring Properties in spring boot

I am trying to create a class that contains values stored in property files in spring boot

so far I have the sample.properties file with the property "source.Ip" set.

The class is as follows:

@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;
    }

}

The property file is directly under src/main/resources which is a source folder.

However I get a :

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

As for my main class it is simply as follows:

@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 content:

source.Ip=127.0.0.1

In order to resolve ${...} placeholders in <bean> definitions or @Value annotations using properties from a PropertySource , you must register a PropertySourcesPlaceholderConfigurer . This happens automatically when using <context:property-placeholder> in XML , but must be explicitly registered using a static @Bean method when using @Configuration classes.

The method must be static for the PropertySourcesPlaceholderConfigurer Because BeanFactoryPostProcessor (BFPP) objects must be instantiated very early in the container lifecycle, they can interfere with processing of annotations such as @Autowired , @Value , and @PostConstruct within @Configuration classes.

Adding this to your application class should do the trick :

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

From the PropertySource documentation .

EDIT

Have you try to

  1. Put the PropertySourcesPlaceholderConfigurer in the AppStarter class.
  2. Move the PropertySource annotation to the AppStarter class.
  3. Remove the Configuration annotation on the PropertyLoader .
  4. Remove the propertyLoader method annotated with Bean.

The problem is probably related to the fact that the PropertyLoader is a component and a configuration class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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