Every application needs at least two environments: one where you can break things safely, and one where you absolutely cannot. Managing those differences through manual file swaps or hardcoded flags is error-prone. Profiles solve this cleanly — you declare the differences, and the framework picks the right one at startup.
One app, many personalities
A profile is simply a named set of configuration that activates under a specific condition. Spring uses profiles to load beans and properties selectively. Maven uses profiles to control how your build behaves — which dependencies to include, which resources to filter.
Defining profiles in pom.xml
You declare Maven profiles inside <profiles>. Each profile can override properties, add dependencies, or configure plugins differently. Activate one by name when you build:
<!-- pom.xml --><profiles> <profile> <id>dev</id> <activation><activeByDefault>true</activeByDefault></activation> <properties> <spring.profiles.active>dev</spring.profiles.active> </properties> </profile> <profile> <id>prod</id> <properties> <spring.profiles.active>prod</spring.profiles.active> </properties> </profile></profiles>
Build for production with:
mvn package -P prod
Profile-specific property files
Sprning Side:
Spring Boot automatically picks up files named application-{profile}.yml. You only need to put the values that differ from the base application.yml:
# application.yml (shared defaults)server: port: 8080spring: datasource: driver-class-name: org.postgresql.Driver
# application-dev.ymlspring: datasource: url: jdbc:postgresql://localhost:5432/myapp_dev username: dev_user password: dev_pass
# application-prod.ymlspring: datasource: url: jdbc:postgresql://prod-db:5432/myapp username: ${DB_USER} # from environment variable password: ${DB_PASSWORD}
Profile-specific beans
You can also activate entire beans conditionally using @Profile. This is useful for swapping implementations — for example, an in-memory fake vs. a real external service:
@Service@Profile("dev")public class FakePaymentService implements PaymentService { ... }@Service@Profile("prod")public class StripePaymentService implements PaymentService { ... }
How activation flows end-to-end
Maven passes the active profile name to Spring via the spring.profiles.active property (set in pom.xml and filtered into your resources). Spring then loads the matching application-{profile}.yml and activates the annotated beans. You can also override this at runtime:
java -jar myapp.jar --spring.profiles.active=prod
This means your CI/CD pipeline, your local machine, and your production server can all run the same JAR with completely different behavior — no code changes required.

Hinterlasse einen Kommentar