Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 66 ยท Inversion of Control and Beans

Conditional Beans

Register Spring beans only when conditions hold: @Profile, @ConditionalOnProperty, @ConditionalOnClass, @ConditionalOnMissingBean and custom Condition classes.

Not every bean should exist in every run. A mock mail sender belongs on a developer's laptop but not in production. A Redis cache makes sense only when Redis is configured. A metrics exporter should switch off when its library is missing. Spring solves all of this with conditions: rules attached to a configuration class or @Bean method that decide, while the container is still registering bean definitions, whether the bean is created at all.

This idea is the engine behind Spring Boot's auto-configuration, so understanding it now makes the next chapter easy. Real Spring annotations are shown read-only. The two TryIts are plain-Java stand-ins that evaluate conditions the way the container does, and each is clear about what is imitation.

Conditions decide if a bean exists

Evaluated early While definitions are registered, before any object is built.
On classes or methods Attach to @Configuration, @Component or @Bean.
Powers Boot Auto-configuration is conditions all the way down.
1 / 2

@Profile

A profile is a named group of beans that is switched on or off by configuration. It is the simplest condition:

Java
@Configuration
public class MailConfig {

    @Bean
    @Profile("dev")
    MailSender consoleMailSender() {
        return new ConsoleMailSender();          // prints instead of sending
    }

    @Bean
    @Profile("!dev")
    MailSender smtpMailSender() {
        return new SmtpMailSender("smtp.example.org");
    }
}

Active profiles come from spring.profiles.active (see Profiles and Environment-Specific Config). @Profile("dev") means "when dev is active". @Profile("!dev") means "when dev is not active". Several names mean or: @Profile({"dev", "test"}) matches either one. For and, combine inside an expression with parentheses, such as @Profile("prod & eu").

Profiles describe the environment. Use them to separate dev, test and production wiring. Do not use them as general feature switches: a property is better for that, as you will see next.

The @Conditional family

@Profile is one member of a larger family built on the core annotation @Conditional, which takes a Condition implementation. Spring Boot ships ready-made, readable versions in the package org.springframework.boot.autoconfigure.condition:

Annotation Beans are created when...
@ConditionalOnProperty a property has a given value (or is set at all)
@ConditionalOnClass a class is on the classpath
@ConditionalOnMissingClass a class is not on the classpath
@ConditionalOnBean another bean already exists
@ConditionalOnMissingBean no bean of that type exists yet
@ConditionalOnWebApplication the app is a web application (servlet or reactive)
@ConditionalOnExpression a SpEL expression evaluates to true
@ConditionalOnResource a resource exists

@ConditionalOnProperty

This is the one you will write most often, as a feature toggle:

Java
@Configuration
public class AuditConfig {

    @Bean
    @ConditionalOnProperty(
        prefix = "shop.audit", name = "enabled",
        havingValue = "true", matchIfMissing = false)
    AuditLog auditLog() {
        return new AuditLog();
    }
}

With shop.audit.enabled=true the bean exists. With the property missing, the bean is absent (matchIfMissing = false is the default). Set matchIfMissing = true when the feature should be on by default and switched off only by an explicit false. Check the exact spelling: a typo in the property name silently leaves the feature off.

@ConditionalOnClass

Libraries use this to react to what is on the classpath:

Java
@Configuration
@ConditionalOnClass(name = "com.zaxxer.hikari.HikariDataSource")
class HikariPoolConfig { ... }

Prefer the name = "..." form (a string) on classes that might be absent: referring to the class literal in a method signature could cause a loading error when the class really is missing. On a whole configuration class, the class-literal form is also safe because Spring reads the annotation without loading the class.

@ConditionalOnMissingBean: back off

This is the most important condition in Boot. It says "create this bean only if the application has not defined one":

Java
@Bean
@ConditionalOnMissingBean
ObjectMapper objectMapper() {
    return new ObjectMapper();                  // Boot's default
}

If you declare your own ObjectMapper bean, Boot's version backs off and yours is used. That is how every default can be replaced without touching the framework: you provide the bean, the default steps aside. It is also why you can often customize behavior by simply defining a bean of the right type.

@ConditionalOnBean and @ConditionalOnMissingBean look at the bean definitions registered so far, so the result depends on the order in which configuration classes are processed. They are reliable inside auto-configuration, which Boot deliberately processes after your own configuration. In your own @Configuration classes the order is hard to predict, so avoid them there and use profiles or properties instead.

A custom condition

When none of the built-ins fits, implement Condition and attach it with @Conditional:

Java
class OnLinuxCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return context.getEnvironment()
            .getProperty("os.name", "")
            .toLowerCase()
            .contains("linux");
    }
}

@Bean
@Conditional(OnLinuxCondition.class)
FileWatcher fileWatcher() { return new InotifyFileWatcher(); }

The ConditionContext gives access to the environment (properties and profiles), the bean registry, the classloader and the resource loader. Package it into your own annotation (meta-annotated with @Conditional) if you use it in several places. That is exactly how @ConditionalOnProperty is built.

A mini condition evaluator

The container asks each candidate "do your conditions hold?" before it registers the definition. The stand-in below does that with a small Condition interface and an annotation-free list of definitions so the logic stays visible. The conditions themselves are real in spirit: property value, class presence and a missing-bean check.

Java A mini condition evaluator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In run 2, mailSender is skipped because a bean of that name already exists: the default backed off. The reasons printed here resemble what Boot prints in its conditions evaluation report, which you will enable in How Auto-Configuration Works.

Profile expressions

@Profile accepts a small expression language: !, & and |, with parentheses when mixing operators. The stand-in below evaluates a simplified version (a list means "or", and each item can be negated) so you can see how active profiles drive the decision.

Java Which beans do these profiles activate?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice how consoleMailSender and smtpMailSender never exist together: one profile and its negation partition the runs. The real implementation parses full expressions, and a bean with no @Profile is always eligible.

Putting conditions to good use

  • Feature toggles: @ConditionalOnProperty with a clear prefix, so operators can switch things on and off with configuration alone.
  • Environment wiring: @Profile for dev, test and production differences such as fake mail, in-memory stores and seeded data.
  • Libraries and starters: @ConditionalOnClass plus @ConditionalOnMissingBean, so defaults appear only when relevant and always yield to the user (Writing Your Own Starter).
  • Keep conditions on the narrowest scope. Put them on a @Bean method when one bean varies, and on a configuration class when a whole group switches together (a failed class condition skips every bean inside).
  • Test both branches. A condition that is never tested is a bug waiting for the environment that flips it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When are conditions such as @ConditionalOnProperty evaluated?

    Conditions decide whether a bean definition is registered at all, so they run during startup while the container processes configuration, not at runtime.
  2. 2. What does @ConditionalOnMissingBean on a default ObjectMapper bean achieve?

    This is the back-off mechanism: if you define your own bean, the default is skipped, so every Boot default can be replaced.
  3. 3. A feature should be ON unless someone sets shop.audit.enabled=false. Which option does that?

    With matchIfMissing = true the condition matches when the property is absent, and an explicit false makes it fail, so the bean is on by default.
  4. 4. What does @Profile({"dev", "test"}) mean?

    Several profile names in one annotation are combined with OR. Use an expression like dev & test when you need AND.

Summary

  • Conditions decide, during registration, whether a configuration class or @Bean method creates beans at all.
  • @Profile ties beans to the environment; !name negates and several names mean OR.
  • Boot's @ConditionalOn... annotations test properties, classpath contents, other beans, web application type and expressions.
  • @ConditionalOnMissingBean lets defaults back off when you define your own bean; use it in auto-configuration, not in ordinary config where order is unclear.
  • A custom Condition plus @Conditional covers everything else.

Next: Application Events and Runners.