@Profile
annotation using which we create profiles. @Profile
is used with @Configuration
and spring stereotypes such as @Component
, @Service
etc. * Different profile is created for different environment. For example we can have environment such as production, development and testing. In development environment we can enable development profile and in production environment we can enable production profile and so on.
* A profile can be activated using (spring.profiles.active)
- property file .properties/.yml
- command line
- an Environment Variable (java -jar abc.jar spring.profiles.active=prod)
- a JVM Property (java -jar -Dspring.profiles.active=prod abc.jar)
- You can set list of profiles like ; java -jar -Dspring.profiles.active="prod,test,x" abc.jar
- programmatically
- Context parameter in web.xml
- @ActiveProfile in test
*We can add active and default profile programmatically by using
ConfigurableEnvironment
*You can also configure profile using spring.profiles.include that will be included for every active profile.
*In spring boot testing we can add active profile by using
@ActiveProfiles
annotation*We can create property file using profile name using the convention
application-{profile}.properties|yml
* In application.yml file you can define active profile using spring.profiles.active=dev
* We can add active profiles using command line with java command. In this case active profile configured in property file will be replaced by active profile passed in command line
* How to set active profile programatically
public static void main(String[] args) { SpringApplication application = new SpringApplication(MyApplication.class); ConfigurableEnvironment environment = new StandardEnvironment(); environment.setActiveProfiles("dev","test"); application.setEnvironment(environment); application.run(args); }
*How to set default profile programatically - 1
public static void main(String[] args) { SpringApplication application = new SpringApplication(MyApplication.class); ConfigurableEnvironment environment = new StandardEnvironment(); environment.setDefaultProfiles("dev","test"); application.setEnvironment(environment); application.run(args); }
* How to set default profile programatically -2
@Profile({"dev","default"})
*You can have negative profile. For example when you are annotating class with @Profile annotation, you can negotiate it. Like @Profile("!dev"). It means
- if dev profile is active this bean won't be created
- if dev profile is not active then this bean will be created. And will belong to any other profile than dev.
Reference/Useful links
No comments:
Post a Comment
Thank you for your comment!