The @SpringBootApplication annotation is a meta-annotation that combines three essential Spring Boot annotations:
@Configuration – Indicates that the class contains Spring bean definitions.
@EnableAutoConfiguration – Enables Spring Boot’s auto-configuration to automatically set up the application based on dependencies.
@ComponentScan – Scans for Spring components (like @Service, @Repository, @Controller) in the current package and sub-packages.
Example:
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Why Use @SpringBootApplication?
Auto-Configures Dependencies – Automatically configures beans based on the classpath.
Component Discovery – Scans for Spring-managed components in the application.
Marks the class as a RESTful web service controller. It combines:
@Controller ((Marks the class as a Spring MVC controller).
@ResponseBody (to return JSON/XML directly)
Example:
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring Boot!";
}
}
public class ProductController {
@RequestMapping(value = "/products", method = RequestMethod.GET)
public String getProducts() {
return "All Products";
}
@RequestMapping(value = "/products", method = RequestMethod.POST)
public String addProduct() {
return "Product added";
}
}
Used to extract values from the URI template.
Example:
@GetMapping("/users/{id}")
public String getUser(@PathVariable Long id) {
// Handles requests like /users/123
return "User ID: " + id;
}
Features:
Extracts values from the path portion of the URL
Parameters are mandatory by default
Useful for RESTful URLs that identify resources
Can specify the path variable name if different: @PathVariable("id") Long userId
Sometimes you have more than one bean (class) of the same type, and Spring doesn't know which one to inject.
@Qualifier helps you tell Spring exactly which bean to use.