Amazon holiday deals See deals →ad

Mets Minor League Blog

Music theory, instruments and musicians

Mets Minor League Blog

Music theory, instruments and musicians

How to Exclude Configuration from a Spring Boot Application

Managing configuration in a Spring Boot application is crucial for tailoring the application’s behavior to different environments or requirements. Sometimes, you may need to exclude certain configuration classes, beans, or properties to prevent conflicts, reduce startup time, or customize behavior for specific deployment scenarios. This guide walks you through the steps to exclude configuration in Spring Boot effectively, ensuring your application runs precisely as intended without unwanted settings.

What You’ll Need

  • Basic understanding of Spring Boot application structure
  • Knowledge of Java annotations and configuration classes
  • Spring Boot project setup (preferably using Maven or Gradle)

Step-by-Step

Using Spring Profiles to Control Configuration

Spring Profiles provide a clean, declarative way to include or exclude entire configuration classes based on the active environment. Annotate a configuration class or a @Bean method with @Profile("name") to make it load only when that profile is active. For example, @Profile("dev") on a @Configuration class will load it only when the dev profile is set via spring.profiles.active=dev in application.properties or as a command-line argument --spring.profiles.active=dev. Conversely, you can exclude a configuration by assigning it to a profile you never activate, or use @Profile("!prod") to load it for all profiles except prod. This approach is especially useful for environment-specific beans like embedded databases, mock services, or logging configurations. Remember that profile annotations are evaluated at runtime, so they do not reduce startup time if the class is still scanned—only the bean creation is skipped.

Excluding Configuration via Property Files

Spring Boot allows you to exclude auto-configuration classes without touching your main class by using the property spring.autoconfigure.exclude in application.properties or application.yml. For instance, spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration will prevent the DataSource auto-configuration from loading. You can list multiple classes separated by commas. This is beneficial when you need to exclude different configurations per environment without recompiling code. For example, in a test profile you might exclude security auto-configuration, while in production you keep it. The property approach is also useful when you cannot modify the main class, such as when using a shared library or a pre-built jar. However, be cautious with typos in class names—Spring Boot will fail at startup if the class cannot be found.

Using @Conditional and @ConditionalOnProperty for Fine-Grained Control

When you need to exclude a specific bean or configuration based on a property value, use @ConditionalOnProperty or the more general @Conditional annotation. For example, @ConditionalOnProperty(name = "app.cache.enabled", havingValue = "true") on a @Bean method will only create that bean if the property is set to true. If the property is missing or set to false, the bean is skipped. This is a powerful way to exclude functionality without modifying the class structure. Similarly, @ConditionalOnClass excludes a configuration if a certain class is not on the classpath, and @ConditionalOnExpression allows complex SpEL conditions. These annotations are evaluated at startup, so they provide a compile-time-like check but still require the class to be scanned. For custom conditions, implement the Condition interface and override matches() to return false when you want to exclude the configuration.

Excluding Beans Using @Bean @ConditionalOnMissingBean

Although often used to provide defaults, @ConditionalOnMissingBean can also help exclude a bean by ensuring that if another bean of the same type exists, your configuration is skipped. For example, if you have a configuration class that defines a RestTemplate bean, annotate that method with @ConditionalOnMissingBean(RestTemplate.class). Then, if you define your own RestTemplate elsewhere (perhaps in a test configuration), the default one will not be created. To actively exclude a bean you don’t want, you can define a dummy bean of the same type in a profile-specific configuration, but this is often overkill. A cleaner method is to use @Bean with a @Profile("!exclude") or to remove the bean definition entirely. Remember that @ConditionalOnMissingBean is evaluated after all bean definitions are read, so it works well for overriding defaults but not for excluding beans that are already explicitly defined.

Common Mistakes to Avoid When Excluding Configuration

  • Excluding too much: Removing auto-configurations like DataSourceAutoConfiguration without providing an alternative can cause startup failures if other beans depend on a DataSource. Always ensure you have a fallback.
  • Using incorrect class names: When using spring.autoconfigure.exclude or the exclude parameter, the class must be fully qualified and present on the classpath. A typo will throw a ClassNotFoundException at startup.
  • Forgetting profile activation: If you use @Profile to exclude configurations, but do not set the active profile, the configuration may still load if the profile is not specified. Use spring.profiles.default to set a fallback.
  • Mixing exclusion methods: Combining exclude in @SpringBootApplication with property-based exclusions can lead to confusion. Stick to one method per configuration class for maintainability.
  • Ignoring conditional evaluation order: Conditions like @ConditionalOnProperty are evaluated before bean creation, but if a property is defined in a profile-specific file, ensure that profile is active.

Frequently Asked Questions

Can I exclude a configuration class that is not auto-configured?

Yes, you can exclude any @Configuration class by using @Import with exclude or by using component scanning filters. For example, @ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = MyConfig.class)) prevents that class from being picked up. This works for your own configuration classes as well as third-party ones.

What is the difference between excluding auto-configuration and using profiles?

Excluding auto-configuration (via exclude or property) completely removes the configuration from the application context, so it is not processed at all. Profiles, on the other hand, conditionally load configurations based on the active profile, but the class is still scanned and evaluated. Exclusions are more aggressive and useful for preventing unwanted defaults, while profiles are better for environment-specific variations.

Can I exclude configuration at runtime after the application has started?

No, Spring Boot’s configuration exclusion is a startup-time operation. Once the application context is refreshed, you cannot dynamically remove or add configuration classes. If you need to change behavior at runtime, use @RefreshScope with Spring Cloud Config or implement a custom BeanFactoryPostProcessor to modify bean definitions before instantiation.

How do I debug why a configuration was not excluded?

Enable debug logging by setting logging.level.org.springframework.boot.autoconfigure=DEBUG in your properties. This will show which auto-configurations were considered and why they were excluded or included. You can also use the ConditionEvaluationReport bean in your code to programmatically inspect the conditions and their outcomes.

How to Exclude Configuration from a Spring Boot Application
Scroll to top