Backend Development 9 min read

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.

<code>@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);
    }
}</code>

The annotation combines three core annotations:

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

@EnableAutoConfiguration

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

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

@Configuration

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

<code>@Configuration
public class WebConfig implements WebMvcConfigurer {}
</code>

@ComponentScan

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

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

@Conditional

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

<code>@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);
    }
}
</code>

@ConditionalOnBean

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

@ConditionalOnMissingBean

Activates configuration only when a specific bean is absent.

<code>@ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
protected static class EmbeddedConfiguration {}
</code>

@ConditionalOnClass

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

<code>@ConditionalOnClass({ RabbitTemplate.class, Channel.class })
public class RabbitAutoConfiguration {}
</code>

@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.

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

@ConditionalOnNotWebApplication

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

@ConditionalOnProperty

Activates configuration when a specific property has a given value.

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

@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.

<code>@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();
}
</code>

@EnableConfigurationProperties

Enables support for @ConfigurationProperties-annotated beans.

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

@AutoConfigureAfter

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

<code>@AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class })
public class MybatisAutoConfiguration implements InitializingBean {}
</code>

@AutoConfigureBefore

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

@Import

Imports one or more @Configuration‑annotated classes.

<code>@Import(CachingConfigurationSelector.class)
public @interface EnableCaching {}
</code>

@ImportResource

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

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

@RestController

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

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

@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.

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

login 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.