Spring: @Profile keeps environment-specific beans out of production

A bean annotated with a profile is only created when that profile is active.

Code
@Bean
@Profile("local")
DataSource h2() { return new EmbeddedDatabaseBuilder().build(); }

@Bean
@Profile("!local")   // everything except local
DataSource mysql(DataSourceProperties props) { return props.initializeDataSourceBuilder().build(); }
Output
SPRING_PROFILES_ACTIVE=local  -> in-memory H2
SPRING_PROFILES_ACTIVE=prod   -> the real MySQL DataSource
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11