How to read multiple properties files in Spring Boot?
Answer:- As we know that application.properties is the default file for Spring Boot. This file will come by default once we will create a Sprint Boot project.
The default properties file will be loading automatically by the Sprint Boot initializer. But if we want to read some different property file which is placed at some different location then we can follow below steps.
If we can see the below directory structure then we will find that I have created one more property file other than the default one which is application.properties and I placed that in /config/db/ folder. Now, we need to load both the properties file using Spring Boot.
STEP 1
database.properties
jdbc.url=jdbc:mysql://localhost:3306/experiments
STEP 2
application.properties
server.port=9494
STEP 3
MultiplePropServicesApplication.java
package com.gaurav.prop.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.ConfigurableEnvironment;
@SpringBootApplication
@ComponentScan("com.gaurav.prop")
public class MultiplePropServicesApplication {
private static Logger logger = LoggerFactory.getLogger(MultiplePropServicesApplication.class);
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(MultiplePropServicesApplication.class)
.properties("spring.config.name:application,database", "spring.config.location:classpath:/, classpath:/config/db/")
.build().run(args);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
logger.info("jdbc.url:->"+environment.getProperty("jdbc.url"));
}
}
Output:-
2018-05-16 10:26:04.207 INFO 13240 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-05-16 10:26:04.207 INFO 13240 --- [ restartedMain] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2018-05-16 10:26:04.208 INFO 13240 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 9494 (http)
2018-05-16 10:26:04.223 INFO 13240 --- [ restartedMain] c.g.prop.test.MultiplePropServicesApplication : Started MultiplePropServicesApplication in 0.792 seconds (JVM running for 506.018)
2018-05-16 10:26:04.223 INFO 13240 --- [ restartedMain] c.g.prop.test.MultiplePropServicesApplication : jdbc.url:->jdbc:mysql://localhost:3306/experiments
Note:- We can see in the output that application successfully reads the property server.port as I mentioned this in the application.properties file and also it reads the property jbdc.url which I placed in database.properties file.
No comments:
Post a Comment