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:
- Auto-Configuration: Automatically configures Spring applications based on the dependencies in the classpath.
- Embedded Servers: Includes embedded servers (Tomcat, Jetty, Undertow) for running applications without external servers.
- Minimal XML Configuration: Provides a convention-over-configuration approach, drastically reducing boilerplate code.
- Production-Ready Features: Offers metrics, health checks, and externalized configuration.
- Faster Development: Spring Boot’s starter dependencies and simplified configuration accelerate the development lifecycle.
2. Key Annotations
@SpringBootApplication
- Combines three annotations:
- @EnableAutoConfiguration: Enables Spring Boot’s auto-configuration mechanism.
- @ComponentScan: Scans the package and its sub-packages for Spring-managed components.
- @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
basePackagesorbasePackageClasses.
- Without
- 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.
- Often used with methods annotated with
- Example:
@Configuration public class AppConfig { @Bean public MyService myService() { return new MyService(); } }
Key Differences:
| Annotation | Primary Role | Additional Notes |
|---|---|---|
@EnableAutoConfiguration | Enables automatic Spring Boot configuration | Automatically configures beans based on the classpath and common patterns. |
@ComponentScan | Scans for components to register as beans | Helps discover classes annotated with @Component, @Service, etc. |
@Configuration | Declares a class as a configuration source | Defines 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
| Scope | Description | Available In Compile? | Runtime? | Packaged? |
|---|---|---|---|---|
| compile (default) | Used during compilation and runtime. Included in final build. | ✅ Yes | ✅ Yes | ✅ Yes |
| provided | Used during compile, but not packaged. Expected at runtime (e.g., servlet API). | ✅ Yes | ❌ No | ❌ No |
| runtime | Not needed at compile time, only at runtime. | ❌ No | ✅ Yes | ✅ Yes |
| test | Used 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
@Controllerand@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:
- Spring scans for
@RestControllerduring component scanning. - Maps incoming HTTP requests to appropriate handler methods.
- Serializes the method’s return value into JSON/XML.
- Spring scans for
- 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
@Controllerannotation is a specialization of the@Componentannotation. - It indicates that the class is a Spring MVC controller.
- Works with
@RequestMappingto 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:
- Monitor application status.
- Expose operational information.
- Debug production issues efficiently.
Common Endpoints:
/actuator/health: Shows application health status./actuator/info: Displays custom application information./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:
- Implement
Endpointor extendAbstractEndpoint.
@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:
- Better Readability: YAML supports nested structures.
- Hierarchical Configurations: YAML allows clear organization of related properties.
Order and Preference:
application.ymltakes precedence overapplication.propertiesif both are present.- 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:
@Getter/@Setter: Generates getters and setters.@Data: Combines@Getter,@Setter,@ToString,@EqualsAndHashCode, and@RequiredArgsConstructor.@Builder: Implements the builder pattern.@NoArgsConstructor,@AllArgsConstructor: Generates constructors.@ToString: Creates atoStringmethod.@EqualsAndHashCode: GeneratesequalsandhashCodemethods.
Example:
@Data
public class User {
private String name;
private int age;
}