First step is to create a project in Spring Initializer using the default values as shown in image. Or if you're integrating in your current project, you can go to the next step.
Create
application.yamlfile in your spring-boot project at location src/main/resources folder.Now create a
.yamlfile for each profile we want to configure. FordevI'm naming my fileapplication-dev.yaml, forstagingapplication-staging.yamlNow in your
pom.xmlfile, copy the following lines
<profiles>
<profile>
<id>dev</id>
<properties>
<activatedProperties>dev</activatedProperties>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>staging</id>
<properties>
<activatedProperties>staging</activatedProperties>
</properties>
</profile>
</profiles>
Over here we're defining our two profiles dev and staging. The line <activeByDefault>true</activeByDefault> means that the profile dev will be active if no profile has been selected while running the spring boot project.
- Now in the
application.yamlfile, put the following lines
spring:
profiles:
active: @activatedProperties@
This would be reading the <activatedProperties> tag in your pom.xml
- In
application-dev.yamlcopy the following lines
spring:
profiles: dev
server:
port: 8093
application:
current-profile: dev
- In
application-staging.yaml
spring:
profiles: staging
server:
port: 8094
application:
current-profile: staging
Notice that the
portproperty inapplication-dev.yamlandapplication-staging.yamlis different.Now, to run the application using
devprofile, run the command
mvn spring-boot:run -Dspring-boot.run.profiles=dev
and for staging
mvn spring-boot:run -Dspring-boot.run.profiles=stagingFor
dev, application will run on port8093and forstaging, on8094.The advantage of using profiles is the we can configure different properties for different environments. Another advantage would be to use different variables in different environments. To show this we can create a class
ActiveProfile.javain the application.Copy the following lines
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class ActiveProfile {
@Value("${application.current-profile}")
private String profile;
@EventListener(ContextRefreshedEvent.class)
public void onStartUp() {
System.out.println("The current profile is : " + profile);
}
}
Annotating onStartUp() function with @EventListener(ContextRefreshedEvent.class) means that, this function would run right after the application is ready.
@Value annotation will pick up the value from either application-dev.yaml or application-staging.yaml depending on which profile you run it with.
- After running the application you'll see that result for the
System.out.printlnwould be eitherdevorstaging
The code for the above tutorial is in the following Github Link
Top comments (0)