Create a Custom Auto-Configuration with Spring Boot

Create a Custom Auto-Configuration with Spring Boot

  • Atualizado
  • Publicado em Spring Boot
  • 3 minutos de leitura

1. Overview

Spring Boot auto-configuration simplifies development by automatically configuring an application based on the dependencies present in the classpath. This eliminates the need to manually define certain beans included in auto-configuration classes.

In this guide, you will learn how to create your own custom auto-configuration in Spring Boot.

2. Setting Up Maven Dependencies

To get started, add the following dependencies to your pom.xml:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>

Download the latest versions of these libraries from the Maven Central Repository.

3. Creating a Custom Auto-Configuration

To create your custom auto-configuration, follow these steps:

3.1 Creating a Custom Auto-Configuration

Create a class annotated with @Configuration:

@Configuration
public class MySQLAutoconfiguration {
// Define your beans here
}

Register the class in the standard file resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports:

com.yourproject.autoconfiguration.MySQLAutoconfiguration

If you want to prioritize your configuration over others, add @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE).

3.1 Creating a Custom Auto-Configuration

Use @Conditional annotations to make the auto-configuration flexible:

  • @ConditionalOnClass: Loads the configuration only if the specified class is present.
  • @ConditionalOnMissingClass: Loads if the specified class is missing.
  • @ConditionalOnBean and @ConditionalOnMissingBean: Conditions bean creation on the existence of another bean.

Example usage with DataSource:

@Configuration
@ConditionalOnClass(DataSource.class)
public class MySQLAutoconfiguration {
// MySQL-specific configuration
}

3.3 Conditional Configuration Based on Properties

Use @ConditionalOnProperty to activate the configuration based on properties in the Spring application.properties file:

@Bean
@ConditionalOnProperty(name = “usemysql”, havingValue = “local”)
@ConditionalOnMissingBean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(“com.mysql.cj.jdbc.Driver”);
dataSource.setUrl(“jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true”);
dataSource.setUsername(“mysqluser”);
dataSource.setPassword(“mysqlpass”);
return dataSource;
}

Define the property in mysql.properties:

usemysql=local

3.4 Auto-Configuration Based on Resources

We can condition configuration on the presence of a resource file:

@ConditionalOnResource(resources = “classpath:mysql.properties”)
Properties additionalProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty(“hibernate.dialect”, “org.hibernate.dialect.MySQLDialect”);
return hibernateProperties;
}

3.5 Creating Custom Conditions

For advanced conditional logic, extend SpringBootCondition:

static class HibernateCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
return ClassUtils.isPresent(“org.hibernate.ejb.HibernateEntityManager”, context.getClassLoader())
? ConditionOutcome.match(“HibernateEntityManager found”)
: ConditionOutcome.noMatch(“HibernateEntityManager missing”);
}
}

4. Testing Auto-Configuration

Create a MyUser entity and a repository to test it:

@Entity
public class MyUser {
@Id
private String email;
}

public interface MyUserRepository extends JpaRepository<MyUser, String> {}

Run a JUnit test:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AutoconfigurationApplication.class)
@EnableJpaRepositories(basePackages = { “com.yourproject.autoconfiguration.example” })
public class AutoconfigurationLiveTest {

@Autowired
private MyUserRepository userRepository;

@Test
public void whenSaveUser_thenOk() {
MyUser user = new MyUser(“user@email.com”);
userRepository.save(user);
}
}

If the DataSource configuration is not manually defined, Spring Boot will apply the auto-configuration we created

5. Disabling Auto-Configuration

To exclude a specific auto-configuration, use @EnableAutoConfiguration(exclude = {MySQLAutoconfiguration.class}) or define it in application.properties:

spring.autoconfigure.exclude=com.yourproject.autoconfiguration.MySQLAutoconfiguration

This application will be built and run in the same way as the docker-message-server.

6. Conclusion

In this guide, you learned how to create a custom auto-configuration in Spring Boot, using class, bean, property, and resource conditions. Additionally, we covered how to test and disable unwanted auto-configurations.

Leverage this approach to make your Spring Boot applications more flexible and modular!

Deixe um comentário