Profiles
@Profile annotation, application-{profile}.properties, activating profiles at runtime
- Create environment-specific configs (dev, staging, prod) with profiles
- Activate profiles via command-line, environment variable, or programmatically
- Use @Profile to conditionally register beans
@ConditionalOnProperty (covered previously) — the two are frequently compared and confused with one another. It also assumes familiarity with Beans, the Bean Lifecycle, and Dependency Injection (@Value). Review those first if needed.Table of Contents
- Quick Recap —
@ConditionalOnProperty - The Problem — Different Configuration Per Environment
- What Is Profiling in Spring Boot?
- Setting the Active Profile
- Setting the Profile Dynamically at Runtime
- The
@ProfileAnnotation - Multiple Active Profiles at Once
- Revisiting the Shared-Codebase Question — Profile vs.
@ConditionalOnProperty - Practice Questions
- Summary
Quick Recap `@ConditionalOnProperty`
Overview
Before diving into profiling, it's worth briefly recalling @ConditionalOnProperty, since this lecture directly builds on and contrasts with it.
Definition
@ConditionalOnPropertysays that a bean is created conditionally — meaning a bean may or may not get created, based on a specific property key/value match inapplication.properties. If the configured value matches the expected value, the bean gets created; otherwise, it does not.
Related Concepts
- The earlier lecture posed a question: "If you have two applications sharing one common codebase, how do you ensure a bean is created for only one application and not the other?"
- The expected answer was
@ConditionalOnProperty. However, many engineers also suggested achieving the same result using@Profile. - This lecture explores that alternative in depth — and ultimately explains why, despite being technically possible, using
@Profilefor this purpose is not the technically correct approach, because@Profileis intended specifically for environment separation, not general-purpose conditional bean creation.
The Problem Different Configuration Per Environment
Overview
To understand why Spring Profiles exist, it helps to first understand the underlying real-world problem: the same application code often needs to run against different configuration values depending on which environment it's deployed in.
Definition
An environment (in this context) refers to a distinct deployment context in which the same application code runs — commonly Local/Development (Dev), QA/Staging, and Live/Production (Prod) — each of which typically requires different configuration values for the exact same underlying settings.
Why This Concept Exists
The same piece of code — say, a database connection class — needs different configuration values depending on where it's running:
- Local/Dev machine: might use empty or dummy credentials (
dev username/dev password), since it's just for local development. - QA/Staging environment: might use dummy but distinct credentials (
QA username/QA password) for testing purposes. - Production/Live environment: requires real, valid credentials (
prod username/prod password) to connect to the actual live database.
Real-World Analogy
Think of a single stage play script (the application code) being performed in three different theaters (Dev, QA, Prod) — each theater has a different lighting rig, sound system, and seating capacity (the configuration). The script (the code) doesn't change, but each performance venue needs its own technical setup instructions.
Internal Working Beyond Just Username/Password
45613 in Dev/QA but a different port (65121) in Prod.
- Connection timeout values — e.g., 1000ms in Dev, 500ms in QA, 50ms in Prod — reflecting the fact that production machines typically have significantly more computing/network resources than development or QA machines.
- Request timeout values
- Throttle values
- Retry values — e.g., you might want more retries configured in Dev than in QA, and more in QA than in Prod.Key Observations
- All of these environment-specific values traditionally would need to live in
application.properties— but a singleapplication.propertiesfile cannot hold three (or more) separate, conflicting sets of values for the same keys simultaneously. - This is precisely the problem that Spring Profiles are designed to solve.
Related Concepts
application.properties/application.yml- Environment-based deployment pipelines (Dev → QA/Staging → Production)
What Is Profiling in Spring Boot?
Overview
Profiling in Spring Boot is the mechanism that allows you to maintain multiple, environment-specific configuration files, and select which one is active at any given time.
Definition
A Profile in Spring Boot is, conceptually, equivalent to an environment. Each profile corresponds to its own dedicated properties file, following the naming convention: ``application-``.properties
Internal Working
Instead of a single application.properties file trying to hold every environment's configuration at once, Spring Boot allows you to define:
1application.properties <-- the DEFAULT configuration2application-dev.properties <-- Dev profile3application-qa.properties <-- QA profile4application-prod.properties <-- Prod profileEach of these files can contain the same configuration keys, but with different values appropriate to that specific environment.
Syntax Example Configuration Files
application.properties (the default):
1username=default_username2password=default_passwordapplication-dev.properties:
1username=dev_username2password=dev_passwordapplication-qa.properties:
1username=qa_username2password=qa_passwordapplication-prod.properties:
1username=prod_username2password=prod_passwordCode Examples
A simple bean consuming these configuration values:
1@Component2public class DBConfig {3
4 @Value("${username}")5 private String username;6
7 @Value("${password}")8 private String password;9
10 @PostConstruct11 public void init() {12 System.out.println("Username: " + username);13 System.out.println("Password: " + password);14 }15}Syntax Breakdown
| Element | Meaning |
|---|---|
@Component | Registers DBConfig as a Spring-managed bean |
@Value("${username}") | Injects the value of the username key from the active properties configuration into this field |
@Value("${password}") | Injects the value of the password key |
@PostConstruct | Runs after the bean is fully constructed and its @Value fields populated — used here simply to print the resolved values |
Step-by-Step Execution No Profile Set
- Application starts. Spring Boot finds
DBConfig, a@Component(default Singleton, eagerly initialized). - IOC constructs the bean, then attempts to resolve its
@Value-annotated fields. - Spring Boot looks to see: has any specific profile been set as active?
- In this scenario, no profile has been set yet — only multiple properties files have been created, but none has been designated "active."
- Since no profile is active, Spring Boot falls back to the default
application.propertiesfile. - It finds
usernameandpasswordthere, and fills in the default values.
Output:
1Username: default_username2Password: default_passwordKey Observations
- If you never explicitly set an active profile, Spring Boot always falls back to the plain
application.propertiesfile as the default configuration source. - Creating multiple
application-files by itself does nothing until you actually tell Spring Boot which one to activate..properties
Setting the Active Profile
Overview
To actually make Spring Boot pick up a specific environment's configuration, you need to explicitly set which profile is active.
Syntax Setting the Default Active Profile in `application.properties`
1spring.profiles.active=qaSyntax Breakdown
| Element | Meaning |
|---|---|
spring.profiles.active | The configuration key that tells Spring Boot which profile(s) should be considered active |
qa | The name of the profile to activate — this must exactly match the suffix used in application-qa.properties |
dev, local, development, qa, stage, prod, etc. Whatever name you choose here must exactly match the corresponding suffix in the application-.properties filename.Internal Working Parent/Child Configuration Merging
application.properties as a kind of "parent" configuration, and application-.properties as a "child" configuration:
- If a configuration key exists in both the parent (application.properties) and the child (application-.properties ), the child's value takes priority.
- If a key exists only in the parent (not in the child), the parent's value is used, since there's nothing to override it with.
- If a key exists only in the child (not in the parent), the child's value is used.Code Examples & Step-by-Step Execution QA Profile Active
application.properties:
1username=default_username2password=default_password3spring.profiles.active=qaapplication-qa.properties:
1username=qa_username2password=qa_passwordStep-by-Step Execution
- Application starts. Spring Boot reads
application.propertiesand seesspring.profiles.active=qa. - It confirms: "a profile has been explicitly requested —
qa." - You'll typically see a log message confirming the active profile has been set to
qa. - Spring Boot now looks for a matching file:
application-qa.properties— found. - When resolving
DBConfig's@Valuefields, Spring Boot checks both the default (application.properties, the "parent") andapplication-qa.properties(the "child"). - Since
usernameandpasswordexist in both files, the child (application-qa.properties) values take priority.
Output:
1Username: qa_username2Password: qa_passwordKey Observations
spring.profiles.activeis the master switch controlling which environment-specific configuration file Spring Boot merges on top of the defaultapplication.properties.- Child (profile-specific) values always win over parent (default) values for any key present in both.
Setting the Profile Dynamically at Runtime
Overview
Hardcoding spring.profiles.active directly inside application.properties works, but it means you'd have to manually edit and redeploy that file every time you switch environments (e.g., from Dev to Production) — which isn't practical. Instead, Spring Boot supports setting the active profile dynamically, at application startup, without touching the properties file.
Why This Concept Exists
In real deployments, you don't want to hardcode dev as the default and then have to remember to change it to prod (and redeploy) every time you push to production. Instead, you want to specify the environment at the moment you start the application — the same codebase and same default configuration file can then be launched differently depending on where/how it's started.
Method 1 Command-Line System Property
Internal Working
Running a Spring Boot application via a tool like IntelliJ's "Run" button is, under the hood, simply executing a Maven command:
1mvn spring-boot:runTo dynamically set the active profile at this point, you pass a system property (-D flag) at startup:
1mvn spring-boot:run -Dspring-boot.run.profiles=prodSyntax Breakdown
| Element | Meaning |
|---|---|
mvn spring-boot:run | The underlying Maven command that actually starts the Spring Boot application |
-D | Sets a system property / environment variable for this run |
spring-boot.run.profiles=prod | Tells the Spring Boot Maven plugin to set spring.profiles.active to prod for this run |
Key Observations
-Dspring-boot.run.profiles=prod at startup, this takes priority over whatever spring.profiles.active value is hardcoded inside application.properties. If you don't provide this flag, Spring Boot simply falls back to whatever default is configured in application.properties.Method 2 Maven Profiles in `pom.xml`
Internal Working
Alternatively, you can define multiple named profiles directly inside your project's pom.xml file, each mapping to a different Spring profile:
1<profiles>2 <profile>3 <id>local</id>4 <properties>5 <spring-boot.run.profiles>dev</spring-boot.run.profiles>6 </properties>7 </profile>8 <profile>9 <id>production</id>10 <properties>11 <spring-boot.run.profiles>prod</spring-boot.run.profiles>12 </properties>13 </profile>14 <profile>15 <id>stage</id>16 <properties>17 <spring-boot.run.profiles>qa</spring-boot.run.profiles>18 </properties>19 </profile>20</profiles>Syntax Breakdown
| Element | Meaning |
|---|---|
| Defines a Maven profile named local, which — when selected — sets the Spring profile to dev |
| A Maven profile named production, mapping to the Spring profile prod |
| A Maven profile named stage, mapping to the Spring profile qa |
| The actual Spring profile value that gets applied when this Maven profile is selected |
Selecting a Maven Profile at Startup
1mvn spring-boot:run -P productionSyntax Breakdown
| Element | Meaning |
|---|---|
-P | Tells Maven to activate a specific block from pom.xml, selected by its |
production | The of the Maven profile block to activate — which, per the pom.xml example above, sets spring-boot.run.profiles=prod |
Key Observations
- Both methods (raw
-Dflag vs.-Pwithpom.xml-defined profiles) achieve exactly the same underlying result — settingspring.profiles.activeat startup. - The
pom.xml-based approach (Method 2) is generally preferred in live/production applications, because the startup command becomes much clearer and more self-documenting — e.g.,-P productionmakes the intent obvious, compared to remembering the raw property syntax each time.
Comparison Table Both Methods
| Aspect | Raw -D Flag | Maven pom.xml Profiles + -P |
|---|---|---|
| Setup required | None — just pass the flag directly at the command line | Requires pre-defining named blocks in pom.xml |
| Startup command | mvn spring-boot:run -Dspring-boot.run.profiles=prod | mvn spring-boot:run -P production |
| Readability/clarity | Less self-documenting — must remember exact property syntax each time | More self-documenting — clear, meaningful profile names (production, stage, local) |
| Common preference in production | Less preferred | ✅ More commonly preferred |
Interview Notes
- Q: What is the priority order between a profile set in
application.propertiesand one set dynamically at startup? → The dynamically-set profile (via-Dflag or-Pwithpom.xml) always takes priority over the hardcoded default inapplication.properties. - Q: Why is the
pom.xml-based approach generally preferred in live applications? → Because the startup command is clearer and more explicit about which environment is being targeted, reducing the chance of accidentally running against the wrong environment.
The `@Profile` Annotation
Overview
Now that profiling itself is understood, we can properly cover the @Profile annotation — which uses this same profiling mechanism to control bean creation.
Definition
The@Profileannotation tells Spring Boot to create a given bean only when a specific profile is currently active. If the active profile doesn't match what's specified in@Profile, that bean is not created.
Syntax
1@Component2@Profile("prod")3public class MySQLConnection {4 public MySQLConnection() {5 System.out.println("MySQL connection bean created");6 }7}1@Component2@Profile("dev")3public class NoSQLConnection {4 public NoSQLConnection() {5 System.out.println("NoSQL connection bean created");6 }7}Syntax Breakdown
| Element | Meaning |
|---|---|
@Profile("prod") | This bean will only be created when the currently active profile is exactly "prod" |
@Profile("dev") | This bean will only be created when the currently active profile is exactly "dev" |
Internal Working Profile Matching
@Profile(...) — conceptually similar to activeProfile.equals("prod").Code Examples & Step-by-Step Execution
Setup:
1# application.properties2username=default_username3password=default_password4spring.profiles.active=qaScenario A — Active Profile Is qa:
Step-by-Step Execution
- Application starts → Spring Boot sets the active profile to
qa(fromspring.profiles.active=qa). - IOC finds
MySQLConnection— Singleton, eligible for eager initialization — but it carries@Profile("prod"). - Spring Boot compares the active profile (
"qa") against the required profile ("prod") → they do not match. - Since the profiles don't match, the
MySQLConnectionbean is not created — its constructor never runs. - IOC finds
NoSQLConnection— carries@Profile("dev"). - Spring Boot compares the active profile (
"qa") against the required profile ("dev") → they do not match. - The
NoSQLConnectionbean is also not created.
Output:
1(neither "MySQL connection bean created" nor "NoSQL connection bean created" is printed)Scenario B — Active Profile Is Dynamically Set to prod:
1mvn spring-boot:run -Dspring-boot.run.profiles=prodStep-by-Step Execution
- Application starts → the active profile is dynamically set to
prod(overriding theqadefault hardcoded inapplication.properties). - IOC finds
MySQLConnection, requiring@Profile("prod"). Active profile is"prod"→ they match. - The
MySQLConnectionbean is created →"MySQL connection bean created"prints. - Because the profile is now
prod, Spring Boot also resolves configuration values fromapplication-prod.properties(the profile-specific "child" file) — so any@Value-injected fields on this bean would resolve to the prod-specific values. - IOC finds
NoSQLConnection, requiring@Profile("dev"). Active profile is"prod"→ they do not match. - The
NoSQLConnectionbean is not created.
Output:
1MySQL connection bean createdKey Observations
@Profile(...)performs a direct match between the bean's required profile and the currently active profile — if they don't match, the bean is simply skipped, exactly like a failed@ConditionalOnPropertycondition.- Whichever mechanism sets the active profile (hardcoded default in
application.properties, or dynamically via-D/-Pat startup) directly determines which@Profile-annotated beans get created.
Related Concepts
@ConditionalOnProperty— a more general-purpose conditional bean creation mechanism, not tied specifically to the concept of "environment."@Valueand profile-specific properties file resolution (parent/child merging, as covered earlier).
Multiple Active Profiles at Once
Overview
Spring Boot also supports specifying more than one active profile simultaneously, using a comma-separated list.
Definition
You can setspring.profiles.activeto a comma-separated list of profile names — this activates all of the listed profiles for the purposes of@Profile-based bean matching, but only one properties file is actually used for@Valueresolution: the last one listed in the comma-separated sequence.
Syntax
1spring.profiles.active=prod,qaSyntax Breakdown
| Element | Meaning |
|---|---|
prod,qa | Both the "prod" and "qa" profiles are considered active simultaneously |
@Profile-annotated bean creation, where you might legitimately want beans tagged for multiple different profiles to all be created together.Code Examples & Step-by-Step Execution
Setup:
1spring.profiles.active=prod,qa1@Component2@Profile("prod")3public class MySQLConnection {4 public MySQLConnection() {5 System.out.println("MySQL connection bean created");6 }7}1@Component2@Profile("qa")3public class NoSQLConnection {4 public NoSQLConnection() {5 System.out.println("NoSQL connection bean created");6 }7}Step-by-Step Execution
- Application starts. Spring Boot registers both
"prod"and"qa"as active profiles. - IOC finds
MySQLConnection, requiring@Profile("prod"). Since"prod"is one of the active profiles → matches → bean is created. - IOC finds
NoSQLConnection, requiring@Profile("qa"). Since"qa"is also one of the active profiles → matches → bean is created. - Both beans get created.
- However, for resolving any
@Value-injected configuration on either bean, Spring Boot only uses one profile-specific properties file — specificallyapplication-qa.properties, sinceqais the last entry in the comma-separated list. - This means both
MySQLConnectionandNoSQLConnection, if they had@Value-injected fields likeusername/password, would both receive the QA-specific values — even thoughMySQLConnectionwas created because of theprodprofile match.
Key Observations
- Bean creation matching via
@Profileconsiders all profiles listed inspring.profiles.active— any bean whose required profile appears anywhere in that comma-separated list gets created. - Configuration value resolution (via
@Valueand profile-specific properties files), however, only uses one file — the last profile listed in the comma-separated sequence.
Common Mistakes
Revisiting the Shared-Codebase Question Profile vs. `@ConditionalOnProperty`
Overview
Returning to the original question posed at the start of this lecture (and inherited from the previous @ConditionalOnProperty lecture): "You have two applications sharing one common codebase — how do you ensure a bean is created only for one application and not the other?"
Demonstrating That `@Profile` *Can* Technically Achieve This
Shared codebase, containing a bean tagged with a custom "profile":
1@Component2@Profile("app1")3public class SharedBean {4 // ...5}Application 1's application.properties:
1spring.profiles.active=app1Application 2's application.properties:
1spring.profiles.active=app2Step-by-Step Execution
- When Application 1 starts, its active profile is set to
"app1". - Spring Boot finds
SharedBean, requiring@Profile("app1")→ matches (since Application 1's active profile is"app1") → bean is created. - When Application 2 starts, its active profile is set to
"app2". - Spring Boot finds the same
SharedBeanclass, still requiring@Profile("app1")→ does not match"app2"→ bean is not created for Application 2.
@Profile with custom, application-specific names (like "app1"/"app2") does successfully control conditional bean creation across two applications sharing a common codebase.Why This Is *Not* the Technically Correct Approach
@Profile in this way is considered technically incorrect, because:
- "app1" and "app2" are not environments — they're arbitrary application identifiers, not concepts like Dev/QA/Prod.
- The naming convention application-app1.properties would be confusing to anyone reading the codebase, because @Profile and the application-.properties naming convention are universally understood by developers as representing deployment environments (Dev, QA, Prod, etc.) — not arbitrary "which application am I" identifiers.
- Using @Profile this way creates confusion about the actual purpose of profiling in the codebase, since anyone reasonably familiar with Spring conventions would expect @Profile-tagged values to correspond to environments, not to "which of several sibling applications is running this shared code."Best Practices
@ConditionalOnProperty — not @Profile — for the shared-codebase, application-specific bean creation use case. @Profile should be reserved specifically for genuine environment separation (Dev vs. QA vs. Production), which is its intended, unambiguous purpose. Repurposing it for arbitrary conditional logic (like distinguishing between sibling applications sharing a codebase) works mechanically but muddies the conventional meaning of profiles for anyone else reading or reviewing the code.Interview Notes
- Q: Can
@Profilebe used to conditionally create beans for reasons unrelated to environment (e.g., distinguishing between two applications sharing a codebase)? → Yes, technically it works — Spring performs a simple string match between the active profile(s) and the value specified in@Profile, regardless of what the string actually represents conceptually. - Q: Is this considered good practice? → No — it's explicitly called out as something a careful code reviewer would likely reject, because
@Profileis conventionally understood to represent deployment environments, and repurposing it otherwise creates confusion.@ConditionalOnPropertyis the technically correct tool for this use case. - Q: What is the core conceptual difference between
@Profileand@ConditionalOnProperty? →@Profileis specifically intended for environment separation (Dev/QA/Prod);@ConditionalOnPropertyis a general-purpose mechanism for conditionally creating any bean based on any arbitrary property key/value match, unrelated to the concept of "environment."
Related Concepts
@ConditionalOnProperty(the technically correct tool for non-environment-based conditional bean creation)- Code review / software design conventions and the importance of naming/annotations conveying accurate intent
Practice Questions
Easy
- What does a Spring "profile" conceptually correspond to?
- What is the naming convention for a profile-specific properties file, e.g., for a profile named
stage? - What configuration key is used to set the active profile inside
application.properties?
Medium
- If a key exists in both
application.propertiesandapplication-qa.properties, and theqaprofile is active, which value wins, and why? - Explain the two different methods for setting the active profile dynamically at application startup (without hardcoding it into
application.properties). - If
spring.profiles.active=dev,prodis set, and a bean is annotated@Profile("dev"), will that bean be created? What about its@Value-injected configuration — which properties file will be used?
Hard
- Explain, step by step, why using
@Profile("app1")and@Profile("app2")to control bean creation across two applications sharing a common codebase is technically possible but considered an incorrect (non-idiomatic) use of the annotation. - A team sets
spring.profiles.active=prodvia the-Dflag at startup, even thoughapplication.propertieshardcodesspring.profiles.active=dev. Explain which value takes effect, and why. - Compare
@ConditionalOnPropertyand@Profilein terms of their intended purpose, and explain why the former is the more appropriate choice for the "shared codebase across two applications" scenario, even though the latter can technically achieve the same outcome.
Summary
- Profiling exists because the same application code often needs different configuration values depending on the environment it's deployed in (Dev, QA, Production) — e.g., different database credentials, URLs/ports, timeouts, retry counts, etc.
- A Spring profile is conceptually equivalent to an environment, backed by a dedicated properties file:
application-..properties - If no profile is explicitly set active, Spring Boot falls back to the plain, default
application.propertiesfile. - The active profile is set via the
spring.profiles.activekey — either hardcoded inapplication.properties, or set dynamically at startup via: - A raw command-line flag:
mvn spring-boot:run -Dspring-boot.run.profiles=prod - Named Maven profiles defined in
pom.xml, selected via-P(generally preferred in production for clarity). - When a profile is active, Spring Boot treats
application.propertiesas a parent andapplication-as a child — child values take priority over parent values for any key present in both..properties @Profile("tells Spring Boot to create a given bean only when the specified profile is currently active — performing what is essentially a string match between the active profile(s) and the annotation's value.") - Multiple profiles can be active simultaneously via a comma-separated list (
spring.profiles.active=prod,qa) — this affects which@Profile-tagged beans get created (any bean matching any listed profile is created), but configuration value resolution (@Value) only uses the last-listed profile's properties file. - Although
@Profilecan technically be repurposed to control bean creation for reasons unrelated to environment (e.g., distinguishing between two sibling applications sharing a common codebase), this is considered technically incorrect usage —@Profileis conventionally understood to represent deployment environments, and repurposing it otherwise creates confusion for anyone reading the code. @ConditionalOnPropertyremains the technically correct tool for general-purpose, non-environment-based conditional bean creation — such as the shared-codebase, two-applications scenario — while@Profileshould be reserved specifically for genuine environment separation.
Mastery check
How well can you recall this?
Finished this lesson?