A bean annotated with a profile is only created when that profile is active.
@Bean
@Profile("local")
DataSource h2() { return new EmbeddedDatabaseBuilder().build(); }
@Bean
@Profile("!local") // everything except local
DataSource mysql(DataSourceProperties props) { return props.initializeDataSourceBuilder().build(); }
SPRING_PROFILES_ACTIVE=local -> in-memory H2
SPRING_PROFILES_ACTIVE=prod -> the real MySQL DataSource
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