Master Spring Boot Core Annotations: @SpringBootApplication and Conditional Config

This article explains the essential Spring Boot annotations—including @SpringBootApplication, @EnableAutoConfiguration, @ComponentScan, and the various @Conditional family—detailing their purposes, composition, and usage with clear code examples for Java backend development.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master Spring Boot Core Annotations: @SpringBootApplication and Conditional Config

@SpringBootApplication

This is the core Spring Boot annotation applied to the main class, marking the application and enabling all Spring Boot capabilities.

@SpringBootApplication
public class BaseWebApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(BaseWebApplication.class);
    }
    public static void main(String[] args) {
        SpringApplication.run(BaseWebApplication.class, args);
    }
}

The annotation combines three core annotations:

// uses @Configuration internally
@SpringBootConfiguration
// imports AutoConfigurationImportSelector
@EnableAutoConfiguration
// component scanning
@ComponentScan

@EnableAutoConfiguration

Enables automatic configuration based on the classpath, allowing Spring Boot to configure beans automatically.

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
    @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {}

@Configuration

Introduced in Spring 3.0 to replace XML configuration files; it configures beans via annotations.

@Configuration
public class WebConfig implements WebMvcConfigurer {}

@ComponentScan

Introduced in Spring 3.1 to replace XML component-scan; it automatically registers beans annotated with @Component in specified packages.

@ComponentScan(basePackages = {"com.pack.a", "com.jack.b"})
public class SqlSessionFactoryConfig {}

@Conditional

Marks a bean or configuration to be loaded only when specified conditions are met.

@Bean
@Conditional({SEEConditional.class})
public ServerEndpointExporter serverEndpointExporter() {
    return new ServerEndpointExporter();
}
public class SEEConditional implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String active = context.getEnvironment().getProperty("app.profiles.active");
        return !"prod".equals(active);
    }
}

@ConditionalOnBean

Activates configuration only when a specific bean is present in the container.

@ConditionalOnMissingBean

Activates configuration only when a specific bean is absent.

@ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
protected static class EmbeddedConfiguration {}

@ConditionalOnClass

Activates configuration only when the specified classes are present on the classpath.

@ConditionalOnClass({ RabbitTemplate.class, Channel.class })
public class RabbitAutoConfiguration {}

@ConditionalOnMissingClass

Activates configuration only when the specified classes are missing.

@ConditionalOnWebApplication

Activates configuration only for web applications. The possible types are ANY, SERVLET, and REACTIVE.

/** Any web application will match. */
ANY,
/** Only servlet-based web application will match. */
SERVLET,
/** Only reactive-based web application will match. */
REACTIVE

@ConditionalOnNotWebApplication

Activates configuration only when the project is not a web application.

@ConditionalOnProperty

Activates configuration when a specific property has a given value.

@Bean
@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", matchIfMissing = true)
public AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) {
    return new RabbitAdmin(connectionFactory);
}

@ConditionalOnExpression

Activates configuration when a SpEL expression evaluates to true.

@ConditionalOnJava

Activates configuration based on the Java version range.

@ConditionalOnResource

Activates configuration when a specific resource exists on the classpath.

@ConditionalOnJndi

Activates configuration when a specific JNDI resource is present.

@ConditionalOnSingleCandidate

Activates configuration when there is only a single bean of the specified type, or multiple beans with one marked as primary.

@ConfigurationProperties

Externalizes configuration; binds and validates properties from files like .properties into beans.

@Bean
@ConfigurationProperties(prefix = DataSourceProperties.PREFIX)
public DataSource dataSource() {
    DataSourceBuilder factory = DataSourceBuilder
        .create(this.properties.getClassLoader())
        .driverClassName(this.properties.getDriverClassName())
        .url(this.properties.getUrl())
        .username(this.properties.getUsername())
        .password(this.properties.getPassword());
    if (this.properties.getType() != null) {
        factory.type(this.properties.getType());
    }
    return factory.build();
}

@EnableConfigurationProperties

Enables support for @ConfigurationProperties-annotated beans.

@Configuration
@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })
@EnableConfigurationProperties(DataSourceProperties.class)
public class DataSourceAutoConfiguration {}

@AutoConfigureAfter

Indicates that an auto‑configuration class should be applied after the specified classes.

@AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class })
public class MybatisAutoConfiguration implements InitializingBean {}

@AutoConfigureBefore

Indicates that an auto‑configuration class should be applied before the specified classes.

@Import

Imports one or more @Configuration‑annotated classes.

@Import(CachingConfigurationSelector.class)
public @interface EnableCaching {}

@ImportResource

Imports one or more Spring XML configuration files, useful for legacy projects.

@ImportResource({ "classpath:spring/application-*.xml" })
@SpringBootApplication
public class AppApplication {}

@RestController

Combines @ResponseBody and @Controller; methods return response bodies directly.

@RestController
@RequestMapping("/users")
public class UsersController {}

@RequestMapping

Maps request paths to controller methods.

@GetMapping

Maps HTTP GET requests.

@PostMapping

Maps HTTP POST requests.

@PatchMapping

Maps HTTP PATCH requests, typically for partial updates.

@PutMapping

Maps HTTP PUT requests to create or replace resources.

@DeleteMapping

Maps HTTP DELETE requests to remove resources.

@RequestBody

Indicates that a method parameter should be bound to the request body.

@PathVariable

Extracts values from URI template variables.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javabackend-developmentConfigurationSpring BootannotationsConditional
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.