Posted on: January 18, 2025 Posted by: rahulgite Comments: 0

Spring Boot: Concepts and Features

Spring Boot is an extension of the Spring Framework that simplifies the process of building and deploying Spring-based applications. It provides a convention-over-configuration approach, eliminating boilerplate code and offering embedded servers for rapid application development.


1. Why Spring Boot Instead of Spring?

Advantages of Spring Boot:

  1. Auto-Configuration: Automatically configures Spring applications based on the dependencies in the classpath.
  2. Embedded Servers: Includes embedded servers (Tomcat, Jetty, Undertow) for running applications without external servers.
  3. Minimal XML Configuration: Provides a convention-over-configuration approach, drastically reducing boilerplate code.
  4. Production-Ready Features: Offers metrics, health checks, and externalized configuration.
  5. Faster Development: Spring Boot’s starter dependencies and simplified configuration accelerate the development lifecycle.

2. Key Annotations

@SpringBootApplication

  • Combines three annotations:
    1. @EnableAutoConfiguration: Enables Spring Boot’s auto-configuration mechanism.
    2. @ComponentScan: Scans the package and its sub-packages for Spring-managed components.
    3. @Configuration: Marks the class as a source of bean definitions.

@EnableAutoConfiguration

  • Automatically configures Spring application based on the dependencies available.
@EnableAutoConfiguration
public class AppConfig {
    public static void main(String[] args) {
        SpringApplication.run(AppConfig.class, args);
    }
}

@ComponentScan

  • Scans for components, services, and configurations in the specified package.
@ComponentScan(basePackages = "com.example")
public class AppConfig {}

Difference Between @EnableAutoConfiguration, @ComponentScan, and @Configuration

These three annotations in Spring have distinct purposes and are often used together in a Spring Boot application. Below is a detailed explanation of their differences and usage.


1. @EnableAutoConfiguration

  • Purpose: Enables Spring Boot’s auto-configuration mechanism, which attempts to automatically configure your Spring application based on the dependencies available on the classpath.
  • Details:
    • Automatically configures Spring beans and settings.
    • Typically used in combination with @SpringBootApplication (which includes it by default).
    • Can be fine-tuned or disabled for specific configurations using properties or exclusions.
  • Example: @EnableAutoConfiguration public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }

2. @ComponentScan

  • Purpose: Scans for Spring-managed components (e.g., @Component, @Service, @Repository, @Controller) within the specified package and its sub-packages.
  • Details:
    • Without @ComponentScan, Spring won’t discover and register components unless explicitly declared in a configuration class.
    • By default, it scans the package of the annotated class and its sub-packages.
    • You can specify the base packages using basePackages or basePackageClasses.
  • Example: @ComponentScan(basePackages = "com.example.myapp") @Configuration public class AppConfig { // Bean definitions or other configurations }

3. @Configuration

  • Purpose: Indicates that the class contains bean definitions that should be managed by the Spring container.
  • Details:
    • Often used with methods annotated with @Bean, which define and return Spring beans.
    • Serves as a replacement for XML-based configuration in modern Spring applications.
    • It is a marker that indicates the class is a source of Spring configuration.
  • Example: @Configuration public class AppConfig { @Bean public MyService myService() { return new MyService(); } }

Key Differences:

AnnotationPrimary RoleAdditional Notes
@EnableAutoConfigurationEnables automatic Spring Boot configurationAutomatically configures beans based on the classpath and common patterns.
@ComponentScanScans for components to register as beansHelps discover classes annotated with @Component, @Service, etc.
@ConfigurationDeclares a class as a configuration sourceDefines beans explicitly with @Bean or serves as a central location for Java-based configuration.

Common Usage Together:

These annotations are often combined under @SpringBootApplication, which is equivalent to using:

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

3. How to Change Port in Spring Boot

  • Using application.properties:
server.port=8081
  • Using application.yml:
server:
  port: 8081
  • Programmatically:
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.setDefaultProperties(Collections.singletonMap("server.port", "8081"));
        app.run(args);
    }
}

4. Can You Override the Embedded Server?

Yes, Spring Boot allows overriding the default embedded server.

  • Using Dependency: Replace Tomcat with Jetty in pom.xml:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

Maven Dependency Scopes Explained

ScopeDescriptionAvailable In Compile?Runtime?Packaged?
compile (default)Used during compilation and runtime. Included in final build.✅ Yes✅ Yes✅ Yes
providedUsed during compile, but not packaged. Expected at runtime (e.g., servlet API).✅ Yes❌ No❌ No
runtimeNot needed at compile time, only at runtime.❌ No✅ Yes✅ Yes
testUsed only in testing — not included in production builds.❌ No❌ No❌ No
system (rare)Like provided, but you have to provide the JAR path manually.✅ Yes✅ Yes❌ No
import (special)Used only in <dependencyManagement> section to import BOMs.❌ N/A❌ N/A❌ N/A

5. Why is Tomcat Embedded?

  • Ease of Deployment: Embedded Tomcat allows developers to package and run applications as standalone JARs.
  • Portability: Eliminates the need for separate server installation.
  • Simplifies Microservices: Useful for lightweight, containerized deployments.

6. How to Disable Default Web Server?

  • Through application.properties:
spring.main.web-application-type=none
  • Programmatically:
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class)
            .web(WebApplicationType.NONE)
            .run(args);
    }
}

7. Disable Auto-Configuration Classes

  • Exclude specific auto-configuration classes:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class Application {}

8. Using Properties in Components from application.properties

  • Example:
app.name=MySpringApp
@Component
public class MyComponent {
    @Value("${app.name}")
    private String appName;

    public void printAppName() {
        System.out.println("Application Name: " + appName);
    }
}

9. @RestController Internally

  • Combines @Controller and @ResponseBody.
  • Annotations Used:
    • @Controller: Marks the class as a Spring MVC controller.
    • @ResponseBody: Ensures the response is serialized directly into JSON or XML.
  • How It Works:
    1. Spring scans for @RestController during component scanning.
    2. Maps incoming HTTP requests to appropriate handler methods.
    3. Serializes the method’s return value into JSON/XML.
  • Example:
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class UserController {

    @GetMapping(value = "/user", produces = MediaType.APPLICATION_XML_VALUE)
    public @ResponseBody User getUser() {
        User user = new User();
        user.setId(1L);
        user.setName("John Doe");
        return user;
    }
}

10. @Controller Internally

  • The @Controller annotation is a specialization of the @Component annotation.
  • It indicates that the class is a Spring MVC controller.
  • Works with @RequestMapping to map HTTP requests to handler methods.
  • Annotations Used:
    • @Component: Makes the class a Spring-managed bean.
    • @RequestMapping: Maps HTTP requests to handler methods.
  • Example:
@Controller
public class ViewController {
    @RequestMapping("/home")
    public String homePage(Model model) {
        model.addAttribute("message", "Welcome to the homepage");
        return "home"; // View resolver maps to home.jsp or home.html
    }
}

11. Actuators: Use, Advantages, and Customization

Use:

Spring Boot Actuator provides insights into application health, metrics, and configurations, making it a critical tool for monitoring and debugging.

Advantages:

  1. Monitor application status.
  2. Expose operational information.
  3. Debug production issues efficiently.

Common Endpoints:

  1. /actuator/health: Shows application health status.
  2. /actuator/info: Displays custom application information.
  3. /actuator/metrics: Provides metrics like memory usage, CPU usage.

How to Expose Endpoints:

  • Enable specific endpoints:
management.endpoints.web.exposure.include=health,info,metrics

Create Custom Actuator Endpoints:

  1. Implement Endpoint or extend AbstractEndpoint.
@RestControllerEndpoint(id = "customEndpoint")
public class CustomEndpoint {
    @GetMapping("/status")
    public String customStatus() {
        return "Custom Actuator Status";
    }
}

Enable HTTP Traces:

  • Add dependency:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  • Enable traces in application.properties:
management.trace.http.enabled=true
management.endpoints.web.exposure.include=trace

Customize Management Server Port:

  • Change the port for actuator endpoints:
management.server.port=9000

12. Why YAML Over Properties?

Advantages:

  1. Better Readability: YAML supports nested structures.
  2. Hierarchical Configurations: YAML allows clear organization of related properties.

Order and Preference:

  1. application.yml takes precedence over application.properties if both are present.
  2. Example:
server:
  port: 8081

13. Lombok: Simplifying Java Code

Lombok reduces boilerplate code by generating methods like getters, setters, and constructors at compile time.

Key Annotations:

  1. @Getter / @Setter: Generates getters and setters.
  2. @Data: Combines @Getter, @Setter, @ToString, @EqualsAndHashCode, and @RequiredArgsConstructor.
  3. @Builder: Implements the builder pattern.
  4. @NoArgsConstructor, @AllArgsConstructor: Generates constructors.
  5. @ToString: Creates a toString method.
  6. @EqualsAndHashCode: Generates equals and hashCode methods.

Example:

@Data
public class User {
    private String name;
    private int age;
}

Leave a Comment