Master Spring Boot Annotations: From @SpringBootApplication to @Conditional

This article provides a comprehensive guide to the most essential Spring Boot annotations, explaining their purpose, usage, and code examples, helping developers configure beans, enable auto‑configuration, and control application behavior effectively.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master Spring Boot Annotations: From @SpringBootApplication to @Conditional

Environment: Spring Boot 2.3.9

@SpringBootApplication

This is the core Spring Boot annotation applied to the main class, marking the application as a Spring Boot app and enabling all of its 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);
    }
}

@EnableAutoConfiguration

Enables automatic configuration; Spring Boot will configure beans based on the classpath and existing beans.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@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 allows bean definitions via annotations.

@Configuration
public class WebConfig implements WebMvcConfigurer {
}

@ComponentScan

Introduced in Spring 3.1 to replace the XML component-scan element; it enables component scanning and automatically registers beans annotated with @Component.

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

@Conditional

Added in Spring 4.0; it activates a bean or configuration 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

Configuration is activated only when a specified bean exists in the container.

@ConditionalOnMissingBean

Configuration is activated only when a specified bean is absent.

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

@ConditionalOnClass

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

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

@ConditionalOnMissingClass

Activates configuration when the specified classes are not present.

@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 when the application 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 when the JVM version falls within a specified range.

@ConditionalOnResource

Activates configuration when a specific resource exists on the classpath.

@ConditionalOnJndi

Activates configuration when the specified JNDI entry is present.

@ConditionalOnSingleCandidate

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

@ConfigurationProperties

Loads external configuration (e.g., .properties files) and can be used on @Configuration classes or @Bean methods.

@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

Works with @ConfigurationProperties to enable support for beans annotated with @ConfigurationProperties.

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

@AutoConfigureAfter

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

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

@AutoConfigureBefore

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

@Import

Introduced in Spring 3.0; imports one or more @Configuration‑annotated classes, widely used in Spring Boot.

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

@ImportResource

Introduced in Spring 3.0; 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; the returned value is written directly to the response body, not to a view.

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

@RequestMapping

Maps HTTP request paths to handler methods or classes.

@GetMapping

Maps HTTP GET requests.

@PostMapping

Maps HTTP POST requests.

@PatchMapping

Maps HTTP PATCH requests, typically used for partial updates.

@PutMapping

Creates a new resource or replaces the representation of an existing resource; PUT is idempotent.

@DeleteMapping

Maps HTTP DELETE requests to remove resources.

@RequestBody

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

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

backend-developmentspring-bootannotationsSpring Framework
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.