Learnitweb

@ConditionalOnClass in Spring Boot

1. What is @ConditionalOnClass in Spring Boot?

The @ConditionalOnClass annotation is used to conditionally register a bean or configuration in Spring Boot only if a specific class (or classes) is present on the classpath.

It is part of Spring Boot’s conditional annotations family and is commonly used in auto-configuration classes or modular application design.

2. Use Case

Use @ConditionalOnClass when:

  • You want to load a configuration only if a certain class is available in the runtime classpath.
  • You are writing optional feature support that depends on 3rd-party libraries (e.g., Redis, MongoDB).
  • You are creating a Spring Boot starter or custom auto-configuration module.
  • You want to avoid ClassNotFoundException when a class is missing.

3. Basic Syntax

@ConditionalOnClass(name = "com.example.SomeLibraryClass")

or

@ConditionalOnClass(SomeLibraryClass.class)

4. Parameters

ParameterTypeDescription
valueClass[]One or more classes to check for presence on the classpath.
nameString[]Fully qualified class name(s) as Strings. Useful when class might not be in classpath at compile-time.

Note: You can use value when the class is available at compile time. Use name to avoid compile errors when the class may not be present.

5. Example: Enable config if a class is on classpath

Let’s say you want to configure a Redis-related bean only if Redis classes are present.

@Configuration
@ConditionalOnClass(name = "org.springframework.data.redis.core.RedisTemplate")
public class RedisAutoConfiguration {

    @Bean
    public RedisService redisService() {
        return new RedisService();
    }
}

This configuration will only be loaded if RedisTemplate is on the classpath (i.e., Redis dependency is available).

6. Example : Combining with @ConditionalOnProperty

This is very common in Spring Boot auto-configuration:

@Configuration
@ConditionalOnClass(name = "com.zaxxer.hikari.HikariDataSource")
@ConditionalOnProperty(name = "app.datasource.enabled", havingValue = "true")
public class HikariDataSourceConfig {

    @Bean
    public DataSource dataSource() {
        return new HikariDataSource(); // Simplified for example
    }
}