Spring Related Profile - vidyasekaran/current_learning GitHub Wiki

From java brain - https://www.youtube.com/watch?v=9dhZ7MEtsrs

Spring profile - we can think of profile as a preset of config values go together in a group to form a profile. by default - whatever config is present in application.yml is default profile.

You can have multiple active profiles - the order we specify it takes precedence. Treat like extension of configuration.

In spring boot project create "application-test.yml" or "application-qa.yml"

Put common properties in common yml and specific ones in other profiles.

you can pass profiles as part of java command line as below. java -jar spring-boot-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=test

Selecting beans by profile

You can specify a profile in a program also - say you have 2 db config files 1 that connects to prod and another dev.

However you should have only only one @Profile active else end in error

@Repository @Profile("dev") public class LocalDataSourceBean{

}

@Repository @Profile("prod") public class ProdDataSourceBean{

}

If no @Profile added then it is @Profile("default")


application-test.yml my: greeting: helloworld from test

application-qa.yml my: greeting: helloworld from qa

In application.yml - specify the profile name which is property file name "application" -test, or -qaand you see that profile specific result

spring.profiles.active: qa

In program

@Value("${my.greeting}") String greet;

Output : helloworld from qa

Check log file to make sure specific profile is active

Reading Values from Config files

Using the environment object in spring boot

Environment is a bean we can autowire and access config values like active profile, its value etc..

@Autowire private Environment env;

@GetMapping("/envdetails") public String envDetails() { return env.toString(); }