Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read data from java properties file using Spring Boot

I have a spring boot application and I want to read some variable from my application.properties file. In fact below codes do that. But I think there is a good method for this alternative.

Properties prop = new Properties(); InputStream input = null;  try {     input = new FileInputStream("config.properties");     prop.load(input);     gMapReportUrl = prop.getProperty("gMapReportUrl"); } catch (IOException ex) {     ex.printStackTrace(); } finally {     ... } 
like image 493
Arif Acar Avatar asked Jul 09 '16 11:07

Arif Acar


People also ask

How do you call a properties file in spring boot?

Another method to access values defined in Spring Boot is by autowiring the Environment object and calling the getProperty() method to access the value of a property file.

How do I read test properties in spring boot?

You can use @TestPropertySource annotation in your test class. Just annotate @TestPropertySource("classpath:config/mailing. properties") on your test class. You should be able to read out the property for example with the @Value annotation.

How do you read a key value pair from properties file in spring boot?

Using the @Value Annotation The @Value annotation in spring boot reads the value from the application properties file and assigns it to a java variable. To read the property, the property key name must be provided in the @Value annotation.


1 Answers

You can use @PropertySource to externalize your configuration to a properties file. There is number of way to do get properties:

1. Assign the property values to fields by using @Value with PropertySourcesPlaceholderConfigurer to resolve ${} in @Value:

@Configuration @PropertySource("file:config.properties") public class ApplicationConfiguration {      @Value("${gMapReportUrl}")     private String gMapReportUrl;      @Bean     public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {         return new PropertySourcesPlaceholderConfigurer();     }  } 

2. Get the property values by using Environment:

@Configuration @PropertySource("file:config.properties") public class ApplicationConfiguration {      @Autowired     private Environment env;      public void foo() {         env.getProperty("gMapReportUrl");     }  } 

Hope this can help

like image 168
Wilson Avatar answered Sep 25 '22 17:09

Wilson