Return to site

๐Ÿƒ๐ŸŽ“ SPRING CERTIFICATION QUESTION: Can you use @Bean together with @Profile?

ยท spring,java

Answer:

๐‘ท๐’“๐’๐’‡๐’Š๐’๐’† is itself meta-annotated with ๐‘ป๐’‚๐’“๐’ˆ๐’†๐’• annotation which means that

it can be applied to methods, and more specifically factory ๐‘ฉ๐’†๐’‚๐’ methods.

Use cases for applying ๐‘ท๐’“๐’๐’‡๐’Š๐’๐’† annotation on the method level:

1. Bean will only be registered in case the application runs with the same active profile declared in ๐‘ท๐’“๐’๐’‡๐’Š๐’๐’† annotation.

2. In case of overloaded ๐‘ฉ๐’†๐’‚๐’ methods chosen ๐‘ท๐’“๐’๐’‡๐’Š๐’๐’† must be the same for all overloaded methods.

If the profile is inconsistent among all overloaded methods, only ๐‘ท๐’“๐’๐’‡๐’Š๐’๐’† of the first declared method will be considered.

Examples of mentioned terms:

๐‘ด๐’†๐’•๐’‰๐’๐’…๐‘ณ๐’†๐’—๐’†๐’๐‘ท๐’“๐’๐’‡๐’Š๐’๐’†๐‘ช๐’๐’๐’‡๐’Š๐’ˆ๐’–๐’“๐’‚๐’•๐’Š๐’๐’ - demonstrates simplistic usage of ๐‘ท๐’“๐’๐’‡๐’Š๐’๐’† annotation applied at method level.

/**
 * Shows basic usage of {@link Profile} annotations applied on method level.
 */
@Configuration
public class MethodLevelProfileConfiguration {

  /**
   * Point in time-related to application startup.
   */
  @Profile("qa")
  @Bean
  public Instant startupInstant() {
    return Instant.now();
  }

  /**
   * Point in time-related to the scheduled shutdown of the application.
   */
  @Bean
  public Instant shutdownInstant() {
    return Instant.MAX;
  }

  /**
   * Point in time of 1970 year.
   */
  @Profile("develop & production")
  @Bean
  public Instant epochInstant() {
    return Instant.EPOCH;
  }
}

#spring #certificationquestion #vcp