Perfiles para entornos
Cambie la configuración según el entorno mediante perfiles
Perfiles para entornos es una lección gratuita de Spring Boot 4 Microservices & REST APIs en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Spring Boot 4 Microservices & REST APIs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Why Profiles Exist
Real applications run in several environments — local, dev, staging, production — each needing different datasources, log levels, and feature toggles. Profiles let one codebase carry many configurations and activate the right set at runtime.
A profile is just a named label. Beans and property files can be tagged so they apply only when that profile is active.
Profile-Specific Property Files
Boot automatically loads application-{profile}.yml on top of the base application.yml. The profile file overrides matching keys while inheriting everything else.
# application.yml (base, always loaded)
spring:
jpa:
show-sql: false
# application-dev.yml (loaded when dev active)
spring:
jpa:
show-sql: true
datasource:
url: jdbc:h2:mem:devdbActivating a Profile
Set spring.profiles.active to choose which profiles run. You can do this in a file, as an environment variable, or on the command line.
# Command line
java -jar app.jar --spring.profiles.active=prod
# Environment variable
export SPRING_PROFILES_ACTIVE=prod
# Multiple profiles
java -jar app.jar --spring.profiles.active=prod,metricsConditional Beans with @Profile
@Profile on a bean or configuration class makes it register only when that profile is active. This is ideal for swapping implementations between environments.
@Configuration
public class PaymentConfig {
@Bean
@Profile("prod")
public PaymentGateway liveGateway() {
return new StripeGateway();
}
@Bean
@Profile("!prod")
public PaymentGateway fakeGateway() {
return new InMemoryGateway();
}
}Profile Expressions
The @Profile value supports simple logic: ! for NOT, & for AND, and | for OR. Group expressions with parentheses.
@Profile("!prod") // anything except prod
@Profile("prod & metrics") // both active
@Profile("dev | test") // either active
@Profile("prod & (eu | us)") // groupedThe Default Profile
When no profile is active, Spring enables the implicit default profile. You can target it explicitly with @Profile("default") for fallback beans used during plain local runs.
@Bean
@Profile("default")
public DataSeeder localSeeder() {
return new SampleDataSeeder();
}Profile Groups
A profile group bundles several profiles under one name, so activating the group activates them all. Great for composing cross-cutting concerns.
spring:
profiles:
group:
production:
- prod
- metrics
- swagger-off
# Now: --spring.profiles.active=production turns on all threeIncluding Profiles
spring.profiles.active sets the primary profiles, while spring.profiles.include adds extra ones unconditionally, regardless of which primary profile is selected.
spring:
profiles:
include:
- common-logging
- auditInspecting Active Profiles at Runtime
You can read active profiles from the Environment bean. This is useful for guard logic or for logging which configuration is live.
@Component
public class StartupLogger {
private final Environment env;
public StartupLogger(Environment env) { this.env = env; }
@PostConstruct
void log() {
System.out.println("Active: "
+ String.join(",", env.getActiveProfiles()));
}
}Profiles in Tests
In integration tests, annotate the class with @ActiveProfiles to force a specific configuration, such as an in-memory database profile.
@SpringBootTest
@ActiveProfiles("test")
class OrderServiceTest {
// loads application-test.yml + @Profile("test") beans
}Common Pitfalls
Watch for these mistakes:
- Forgetting to set
spring.profiles.activein production, so dev defaults leak in - Putting secrets in
application-dev.ymland committing it - Overusing
@Profilewhere a simple property toggle would do
Quick Check
Test your grasp of profile expressions.
Recap
Profiles tailor one codebase to many environments.
application-{profile}.ymloverrides base config- Activate via
spring.profiles.active(file, env var, or CLI) @Profileconditionally registers beans, with!,&,|expressions- Profile groups bundle related profiles
- Use
@ActiveProfilesin tests
Preguntas frecuentes
¿La lección «Perfiles para entornos» es gratis?
Sí — el texto completo de «Perfiles para entornos» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Spring Boot 4 Microservices & REST APIs, actualiza a CoddyKit PRO. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.
¿Qué aprenderé en «Perfiles para entornos»?
Cambie la configuración según el entorno mediante perfiles Practicas Spring Boot 4 Microservices & REST APIs con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Spring Boot 4 Microservices & REST APIs?
No se requiere experiencia previa. Spring Boot 4 Microservices & REST APIs en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «Perfiles para entornos»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Spring Boot 4 Microservices & REST APIs?
Sí. Cada lección de Spring Boot 4 Microservices & REST APIs incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- application.properties y YAML
- Perfiles para entornos
- Configuración segura con tipos mediante @ConfigurationProperties
- Configuración externalizada y sobrescritura