We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 12
ozrtv2023 18.45, ‘Spring Profles | Baeldung
”
Spring Profiles
zy
(tiv, Chatine et Fegay time
Groupe cone
Y thitos//ads freestarcom/?
Last updated: May 2, 2023
\Witten by: Eugen Paraschiv (https //wwecbaeldung.com/author/eugen)
Spring (https://wwwbaeldung.com/category/spring) +
Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics)
Get started with Spring 5 and Spring Boot 2, through the reference Learn
Spring course:
>> LEARN SPRING (/1s-course-start)
-
C
¥
tutm_campaign-branding&utm_mec ‘SJButm_content-bacldung.incontent
hitpssvww-baeldung.com/spring-profles aneozrtv2023 18.45, ‘Spring Profles | Baeldung
“ 2
1. Overview
In this tutorial welll focus on introducing Profiles in Spring.
Profiles are a core feature of the framework — allowing us to map our beans to different profiles — for
example. dey, test, and prod.
We can then activate different profiles in different environments to bootstrap only the beans we need.
Further reading:
Configuring Separate Spring DataSource for Tests (/spring-testing-separate-
data-source)
‘Auick practical tutorial on how to configure a separate data source for testing in a Spring application.
Read more (/spring-testing-separate-data-source) —>
Properties with Spring and Spring Boot (/properties-with-spring)
“Tutorial for how to work with properties fles and property values in Spring,
Read more (/properties-with-spring) +
2, Use @Profile on a Bean
Lets start simple and look at how we can make a bean belong to a particular profile, We use the @Profile
annotation — we are mapping the bean to that particular profile; the annotation simply lakes the names of
one (or multiple) profiles
Consider basic scenario: We have a bean that should only be active during development but not deployed in
production.
(https//ads freestarcom/?
We annotate that bean with a dev profile, and it will only be present in the container during development. In
production, the dev simply wont be active
econponent oO
@Profite("éev")
public class DevatasourceContig
hitpssvww-baeldung.com/spring-profles aneoarii2023 18.45 ‘Spring Profles | Baeldung
As 2 quick sie note, profile namgs can also be prefixed with a NOT operator, €,!dev, to exclude them froma
pr
In the example, the component is activated only ifthe dev profile is not active:
component oO
errofi
public class Devoatasourcecontig
3. Declare Profiles in XML
Profiles can also be configured in XML. The tag has a profileallribute, which lakes comma-separated.
values of the applicable profiles
eons protite-téev">
beer id-tdevdatosourcetontig® UO
lase"org. as ldong.proes,DovOatasourceconfig" (>
canes
4. Set Profiles
‘The next stop is to activate and set the profiles so that the respective beans are registered in the container.
Bi re re
Digital train date Get move done: SAS Vyas Get more done: SAS Viyaisa
raductive Aland Analtes raductive Aland Analytics
Tl ratom pl iis P P iis B
Biss mss
(https//ads freestarcom/?
This can be done in a variety of ways, which well explore in the following sections.
4.1. Programmatically via WebApplicationinitializer Interface
Inweb applications, Web4pplicationhnitializercan be used to configure the ServletContext programmatically.
It's also a very handy location to set our active profiles programmatically
cont iguration oO
public class MywebaspLicationInitializer
“Implements WebAcplicationnitializer {
override
pUBLic Vols onStartup(ServietContext servletContext) throws Serviettxception (
servietContext setlnitParazeter(
“epring.profites.active", "dev");
htipsilwnww.bacldung.comispring-profiles ane2/2008 18.45 Spring Profles | Baldung
4.2. Programmatically via ConfigurableEnvironment
We can also set profiles directly on the environment
ehutowired oO
private Configurabletnvirontent envi
‘env. setactiveProfiles("soneProfile");
4.3. Context Parameter in web.xml
Similarly, we can define the active profiles in the web.xmi fle of the web application using a context parameter:
Oo
“ /MEB-INF2pp-contig.xol
“ spring. profiles. actve
“paren-velUe> deve /psren-velue>
4.4, JVM System Parameter
‘The profile names can also be passed in via a JVM system parameter. These profiles will be activated during
application startup:
4.5. Environment Variable
Ina Unix environment, profiles can also be activated via the environment variable:
[ ser rnc retin setts
4.6. Maven Profile
‘Spring profiles can also be activated via Maven profiles by specifying the
spring profiles.active configuration property.
In every Maven profile, we can set a spring profiles active property:
ldung.comispring-profiles
ane,oarii2023 18.45 Spring Profles | Baeldung
-orofiles “ oO
deodeve/4e>
activation
true
dev
«properties?
“spring.profiles.active>prod/soring.profiles.active>
Its value will be used to replace the @spring.profles active@ placeholder in application propertios:
soring. profiles activeresoring protien actives oO
Now we need to enable resource filtering in pom xmt
ctuite oO
edirectorysre/main/resoureesc/directory>
filtering» trucc/#ilterire>
and append a -P parameter to switch which Maven profile will be applied
myn clean package -Pprod O
This command will package the application for the prod profile. It also applies the spring profles.active value
‘prodifor this application when itis running,
> Vopr >
Digital train date Restauration-Expérience cle
atom
ANASUC The Arf Sgt
(nttps://ads freestarcom/?
4.7. @ActiveProfile in Tests
Tests make it very easy to specify what profiles are active using the @ActiveProfile annotation to enable specific
profiles:
aacciverrofites("dev")
htipsilwnww.bacldung.comispring-profiles sinoarii2023 18.45 ‘Spring Profles | Baeldung
So far, we've !20%0d 2 multiote ays of activating profiles. Lets now see which one has priority over the other
‘ar what happens ifwe usc moté than one, from highest to lowest priority
1. Context parameter in web xml
2. WebApplicationinitiaizer
3.JVM System parameter
4 Environment variable
5,Maven profile
5. The Default Profile
‘Any bean that doos not specify a profile bolongs to the default profile.
Spring also provides a way to set the default profile when no other profile is active — by using the
spring.profiles default property.
6. Get Active Profiles
Spring's active profiles drive the behaviour of the @iProfile annotation for enabling/disabling beans, However
\we may also wish to access the list of actve profies programmatically
\We have two ways to do it using Environment or spring profilesactive.
6.1. Using Environment
We can access the active profiles from the Environment object by injecting it
public class mrofttenenger ¢ O
eeutored
private environment enviroments
public void getActiverrafites() <
for (String profilelane : environment. getActiverrofites()) {
systen.out printla(*Currently active profile - "+ profileNane):
>
6.2. Using spring profiles.active
Alternatively, we could access the profiles by injecting the property spring profiles active
» Q
value(s (spring. profile:
private String activeProfile;
htipsilwnww.bacldung.comispring-profiles en2oarii2023 18.45 ‘Spring Profles | Baeldung
Hera, our actizeProf'e variable wilt contain the name of the profile that is currently active, and ifthere are
several. itt contain their narnes Separated by a comma,
However, we should consider what would happen if there is no active profile at all. With our code above, the
absence of an active profile would prevent the application context from being created. This would result in an
MlegalArgumentException owing to the missing placeholder for injecting into the variable.
In order to avoid this, we can define a default value
value *s(spring. profi. scttve:}*)
Seivate string scwerotite O
Now, ifne profiles are active, our activeProfile willust contain an empty string.
‘And if we want to access the list of them just lke in the previous example. we can do it by spliting (/java-split-
string) the activeProfile variable:
public class FrofiteMansger ¢
evalue("S{spring.profiles-active:}*)
private String activerrorites:
public String getActiverrofites() (
for (String profilelane : activeProfites.sptit(",")) (
Systen.out.println("Currently active profile ~ "+ profiteNane);
>
7. Example: Separate Data Source Configurations Using Profiles
Now that the basics are out of the way let's take a look at a real example.
Consider a scenario where we have to maintain the data source configuration for both the development and
production environments.
Let's create a common interface DatasourceConfig that needs to be implemented by both data source
implementations:
public interface OatasourceCentig é
public void setupt) ;
>
Following is the configuration for the development environment:
htipsilwnww.bacldung.comispring-profiles m2