Perfis para ambientes
Alterne a configuração por ambiente usando perfis.
Perfis para ambientes é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Boot 4 Microservices & REST APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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
Perguntas Frequentes
A aula “Perfis para ambientes” é grátis?
Sim — o texto completo de “Perfis para ambientes” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Boot 4 Microservices & REST APIs, atualize para CoddyKit PRO. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.
O que vou aprender em “Perfis para ambientes”?
Alterne a configuração por ambiente usando perfis. Você pratica Spring Boot 4 Microservices & REST APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Spring Boot 4 Microservices & REST APIs?
Nenhuma experiência prévia é necessária. Spring Boot 4 Microservices & REST APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.
Quanto tempo leva a aula “Perfis para ambientes”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Spring Boot 4 Microservices & REST APIs?
Sim. Cada aula de Spring Boot 4 Microservices & REST APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- application.properties e YAML
- Perfis para ambientes
- Configuração segura quanto a tipos com @ConfigurationProperties
- Configuração externa e substituível