package com.example.autoconfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyAutoConfiguration { @Bean public String myBean() { return "AutoConfiguredBean"; } }
Without @ConditionalOnClass, Spring Boot does not check for the presence of any class before creating the bean. So the bean is always created, which can cause errors if the bean depends on missing classes.
Auto-configuration classes are annotated with @Configuration. The @EnableAutoConfiguration annotation is used on the main application class to enable auto-configuration.
Spring Boot loads auto-configuration classes listed under the key org.springframework.boot.autoconfigure.EnableAutoConfiguration in META-INF/spring.factories. If the class is missing or the key is wrong, the auto-configuration won't be loaded.
@ConditionalOnMissingBean ensures that the auto-configuration provides a default bean only if the user has not defined one already, allowing customization.
@ConditionalOnClass prevents the auto-configuration class from being processed if the specified class is missing, so the bean is not created and no error occurs.