Spring Boot Topic

Spring Boot Starters

Spring Boot Starters are dependency descriptors that simplify Maven/Gradle configuration by bundling common dependencies together for specific functionalities.

1. What are Spring Boot Starters?

Definition

Starters are a set of convenient dependency descriptors that you can include in your application. They contain all the necessary dependencies and auto-configuration for specific features.

Benefits

  • Simplified Dependency Management: One starter instead of multiple individual dependencies

  • Auto-configuration: Automatic setup of common configurations

  • Version Management: Compatible versions managed by Spring Boot

  • Production-ready: Often include metrics, health checks, and other production features

2. Core Spring Boot Starters

spring-boot-starter

Purpose: Core starter, including auto-configuration support, logging, and YAML

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

Includes: spring-core, spring-context, spring-boot, spring-boot-autoconfigure, logging

spring-boot-starter-web

Purpose: Building web applications, including RESTful applications

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Includes:

  • spring-web, spring-webmvc

  • Tomcat embedded container

  • Jackson (JSON processing)

  • Validation API

  • Spring Boot autoconfiguration

Auto-configures:

  • DispatcherServlet

  • Jackson ObjectMapper

  • Embedded Tomcat

  • Static content serving

  • Error handling

spring-boot-starter-data-jpa

Purpose: Java Persistence API with Hibernate

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Includes:

  • spring-data-jpa

  • Hibernate

  • JPA API

  • Spring ORM

  • Transaction management

Auto-configures:

  • DataSource

  • EntityManagerFactory

  • TransactionManager

  • Spring Data JPA repositories

spring-boot-starter-test

Purpose: Testing Spring Boot applications

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Includes:

  • JUnit 5

  • Spring Test

  • Mockito

  • Hamcrest

  • AssertJ

  • JSONassert

  • JsonPath

3. Commonly Used Starters

Database Starters

spring-boot-starter-jdbc

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

Use Case: Traditional JDBC operations
Auto-configures: DataSource, JdbcTemplate

spring-boot-starter-data-mongodb

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Use Case: MongoDB database operations
Auto-configures: MongoClient, MongoTemplate

spring-boot-starter-data-redis

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Use Case: Redis caching and messaging
Auto-configures: RedisConnectionFactory, RedisTemplate

Security Starters

spring-boot-starter-security

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Includes: Spring Security core, web, config, LDAP, OAuth2
Auto-configures:

  • Default security configuration

  • Basic authentication

  • CSRF protection

  • Session management

Example Configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authz -> authz
                .requestMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin(form -> form
                .loginPage("/login")
                .permitAll()
            );
        return http.build();
    }
    
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(user);
    }
}

spring-boot-starter-oauth2-client

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

Use Case: OAuth2 and OpenID Connect client support

Messaging Starters

spring-boot-starter-amqp

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

Use Case: RabbitMQ messaging
Auto-configures: RabbitTemplate, RabbitConnectionFactory

spring-boot-starter-kafka

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-kafka</artifactId>
</dependency>

Use Case: Apache Kafka messaging
Auto-configures: KafkaTemplate, ConsumerFactory, ProducerFactory

Example Configuration:

@Configuration
@EnableKafka
public class KafkaConfig {
    
    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;
    
    @Bean
    public ProducerFactory<String, String> producerFactory() {
        Map<String, Object> configProps = new HashMap<>();
        configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        return new DefaultKafkaProducerFactory<>(configProps);
    }
    
    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }
}

Cloud & Microservices Starters

spring-cloud-starter-config

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

Use Case: External configuration management with Spring Cloud Config

spring-cloud-starter-netflix-eureka-client

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

Use Case: Service registration and discovery with Eureka

4. Production & Monitoring Starters

spring-boot-starter-actuator

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Purpose: Production-ready features for monitoring and managing your application

Endpoints:

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,env
  endpoint:
    health:
      show-details: always
    metrics:
      enabled: true

Available Endpoints:

  • /actuator/health - Application health information

  • /actuator/metrics - Application metrics

  • /actuator/env - Environment properties

  • /actuator/info - Application information

  • /actuator/loggers - Configure log levels

Custom Health Indicator Example:
@Component
public class DatabaseHealthIndicator implements HealthIndicator {
    
    @Autowired
    private DataSource dataSource;
    
    @Override
    public Health health() {
        try (Connection connection = dataSource.getConnection()) {
            if (connection.isValid(1000)) {
                return Health.up()
                    .withDetail("database", "Connected successfully")
                    .build();
            }
        } catch (SQLException e) {
            return Health.down(e)
                .withDetail("database", "Connection failed")
                .build();
        }
        return Health.down().withDetail("database", "Unknown error").build();
    }
}

5. Custom Starter Creation

Step 1: Create Auto-configuration

Maven Structure:

custom-starter/
├── pom.xml
└── src/
    └── main/
        ├── java/
        │   └── com/
        │       └── example/
        │           └── starter/
        │               ├── CustomService.java
        │               ├── CustomAutoConfiguration.java
        │               └── CustomProperties.java
        └── resources/
            └── META-INF/
                └── spring.factories

CustomProperties.java:

@ConfigurationProperties(prefix = "custom.service")
public class CustomProperties {
    private String apiKey;
    private String endpoint = "https://api.example.com";
    private int timeout = 5000;
    
    // getters and setters
    public String getApiKey() { return apiKey; }
    public void setApiKey(String apiKey) { this.apiKey = apiKey; }
    public String getEndpoint() { return endpoint; }
    public void setEndpoint(String endpoint) { this.endpoint = endpoint; }
    public int getTimeout() { return timeout; }
    public void setTimeout(int timeout) { this.timeout = timeout; }
}

CustomService.java:

public class CustomService {
    private final CustomProperties properties;
    
    public CustomService(CustomProperties properties) {
        this.properties = properties;
    }
    
    public String process(String data) {
        // Implementation using properties
        return "Processed: " + data + " with API key: " + properties.getApiKey();
    }
}

CustomAutoConfiguration.java:

@Configuration
@ConditionalOnClass(CustomService.class)
@EnableConfigurationProperties(CustomProperties.class)
@ConditionalOnProperty(prefix = "custom.service", name = "enabled", havingValue = "true", matchIfMissing = true)
public class CustomAutoConfiguration {
    
    @Bean
    @ConditionalOnMissingBean
    public CustomService customService(CustomProperties properties) {
        return new CustomService(properties);
    }
}

spring.factories:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.starter.CustomAutoConfiguration

Step 2: Configuration Metadata

additional-spring-configuration-metadata.json:

{
  "properties": [
    {
      "name": "custom.service.api-key",
      "type": "java.lang.String",
      "description": "API key for the custom service",
      "sourceType": "com.example.starter.CustomProperties"
    },
    {
      "name": "custom.service.endpoint",
      "type": "java.lang.String",
      "description": "Service endpoint URL",
      "defaultValue": "https://api.example.com"
    },
    {
      "name": "custom.service.timeout",
      "type": "java.lang.Integer",
      "description": "Request timeout in milliseconds",
      "defaultValue": 5000
    }
  ]
}

Step 3: Using the Custom Starter

In another project's pom.xml:

<dependency>
    <groupId>com.example</groupId>
    <artifactId>custom-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</dependency>

application.properties:

custom.service.api-key=your-api-key-here
custom.service.endpoint=https://api.custom.com
custom.service.timeout=3000

Using in Service:

@Service
public class MyBusinessService {
    
    private final CustomService customService;
    
    public MyBusinessService(CustomService customService) {
        this.customService = customService;
    }
    
    public void processData() {
        String result = customService.process("some data");
        System.out.println(result);
    }
}

6. Starter Best Practices

1. Naming Conventions

  • Use spring-boot-starter-{name} for core starters

  • Use {project}-spring-boot-starter for third-party starters

2. Conditional Configuration

@Configuration
@ConditionalOnClass({SomeClass.class})
@ConditionalOnProperty(prefix = "service", name = "enabled")
@ConditionalOnWebApplication
@ConditionalOnMissingBean(SomeService.class)
public class MyAutoConfiguration {
    // Configuration only applied when conditions are met
}

3. Common Conditions

  • @ConditionalOnClass - When specific classes are on classpath

  • @ConditionalOnMissingBean - When bean doesn't exist

  • @ConditionalOnProperty - When property is set

  • @ConditionalOnWebApplication - When running in web application

  • @ConditionalOnExpression - Custom SpEL expression

4. Configuration Properties

@ConfigurationProperties(prefix = "app.service")
@Validated
public class ServiceProperties {
    @NotBlank
    private String url;
    
    @Min(1000)
    @Max(30000)
    private int timeout = 5000;
    
    // getters and setters
}

7. Troubleshooting Common Issues

Auto-configuration Debug

properties

# application.properties
debug=true

Check Loaded Auto-configurations

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.setLogStartupInfo(false);
        app.run(args);
    }
}

Exclude Auto-configuration

@SpringBootApplication(exclude = {
    DataSourceAutoConfiguration.class,
    SecurityAutoConfiguration.class
})
public class Application {
    // ...
}

Spring Boot Starters significantly reduce configuration overhead and ensure that all dependencies work well together with compatible versions. They follow the convention-over-configuration principle, allowing developers to focus on business logic rather than infrastructure setup.

 

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?