@spring Boot Annotations
@spring Boot Annotations
Spring Boot
Boot Basics
reference
Spring Annotations
1. Overview
Spring Boot made configuring Spring easier with its auto-configuration feature.
In this quick tutorial, we’ll explore the annotations from
the org.springframework.boot.autoconfigure and org.springframework.boot.autoconfigure.co
ndition packages.
2. @SpringBootApplication
We use this annotation to mark the main class of a Spring Boot application:
@SpringBootApplication
class VehicleFactoryApplication {
3. @EnableAutoConfiguration
@EnableAutoConfiguration, as its name says, enables auto-configuration. It means
that Spring Boot looks for auto-configuration beans on its classpath and automatically
applies them.
Note, that we have to use this annotation with @Configuration:
@Configuration
@EnableAutoConfiguration
class VehicleFactoryConfig {}Copy
4. Auto-Configuration Conditions
Usually, when we write our custom auto-configurations, we want Spring to use them
conditionally. We can achieve this with the annotations in this section.
We can place the annotations in this section on @Configuration classes or @Bean methods.
In the next sections, we’ll only introduce the basic concept behind each condition. For further
information, please visit this article.
4.3. @ConditionalOnProperty
With this annotation, we can make conditions on the values of properties:
@Bean
@ConditionalOnProperty(
name = "usemysql",
havingValue = "local"
)
DataSource dataSource() {
// ...
}Copy
4.4. @ConditionalOnResource
We can make Spring to use a definition only when a specific resource is present:
@ConditionalOnResource(resources = "classpath:mysql.properties")
Properties additionalProperties() {
// ...
}Copy
@Bean
@ConditionalOnExpression("${usemysql} && ${mysqlserver == 'local'}")
DataSource dataSource() {
// ...
}Copy
4.7. @Conditional
For even more complex conditions, we can create a class evaluating the custom condition.
We tell Spring to use this custom condition with @Conditional:
@Conditional(HibernateCondition.class)
Properties additionalProperties() {
//...
}Copy
5. Conclusion
In this article, we saw an overview of how can we fine-tune the auto-configuration process
and provide conditions for custom auto-configuration beans.