liveBook · Manning

@profile

As explained in Spring in Action, Sixth Edition

@Profile is a Spring annotation that restricts bean or configuration-class creation to specified active profiles.

@Profile is a Spring annotation that conditionally creates a bean or configuration class when a specified profile is active. Profiles separate development, testing, and production behavior without changing application code. section 6.3.3 section 6.3

Use @Profile to control when application components are created:

  • Apply @Profile("dev") to create a bean only with the dev profile active. section 6.3.3
  • Apply @Profile({"dev", "qa"}) to create a bean when either dev or qa is active. section 6.3.3
  • Apply @Profile("!prod") to create a bean unless the prod profile is active. section 6.3.3
  • Annotate an entire @Configuration class to conditionally create all beans declared in that class. section 6.3.3

Avoid loading development data in production

A CommandLineRunner that loads ingredient data into an embedded database can be limited to development: @Bean followed by @Profile("dev") creates it only for the dev profile. To allow development and testing, use @Profile({"dev", "qa"}); to allow it everywhere except production, use @Profile("!prod"). section 6.3.3

@Bean
@Profile("dev")
public CommandLineRunner dataLoader(IngredientRepository repo,
      UserRepository userRepo, PasswordEncoder encoder) {
 
  ...
 
}

Inspect the complete @Bean and @Profile("dev") declaration for a development-only CommandLineRunner. section 6.3.3

@Bean
@Profile("!prod")
public CommandLineRunner dataLoader(IngredientRepository repo,
      UserRepository userRepo, PasswordEncoder encoder) {
 
  ...
 
}

Inspect the negated profile form that prevents the bean from being created when production is active. section 6.3.3

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains annotation placement, multiple profiles, negation, and configuration-class scope, but stops short of annotation internals.
Examples
Uses a development-only CommandLineRunner, dev-or-qa activation, production negation, and a DevelopmentConfig class.
What it assumes
Assumes basic Spring beans, Java configuration, @Configuration classes, and runtime profile activation.
What you can do after
Operate/configure Spring applications by enabling or excluding beans for selected runtime profiles.
How it connects
Connects Spring profiles with conditional configuration, beans, configuration classes, configuration properties, and active profiles.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.