Common Spring Boot Annotations and Why We Use Them?
- @SpringBootApplication**
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Why we use?
This is the main annotation for Spring Boot application.
It combines 3 annotations internally:
- @Configuration
- @EnableAutoConfiguration
- @ComponentScan
Meaning:
=> Starts Spring Boot app
=> Automatically configures project
=> Scans classes like controller, service, repository
2. @RestController
@RestController
public class StudentController {
}
@RestController is used in Spring Boot to create REST APIs and send data directly to the client as an HTTP response, usually in JSON format.
Why do we use it?
We use @RestController when we want to:
=> send data to frontend applications
=> create APIs
=> return JSON/XML instead of HTML pages
3.@Controller
@Controller is used to create a web controller in Spring MVC.
It is mainly used to return:
=> HTML pages
=> JSP pages
=> Thymeleaf templates
instead of JSON data.
Why do we use @Controller?
We use @Controller when we want to:
=> handle web requests
=> return UI pages to the browser
=> build traditional web applications
Example
@Controller
public class HomeController {
@GetMapping("/home")
public String home() {
return "home";
}
}
4.@Service
@Service is used to mark a class as a service layer in a Spring Boot application.
It contains the business logic of the application.
Why do we use @Service?
We use @Service to:
=> write business logic
=> perform calculations
=> validate data
=> process application logic
=> keep controller code clean
Example
@Service
public class StudentService {
public String getMessage() {
return "Welcome Student";
}
}
5. @Repository
@Repository is used to mark a class as a repository layer in a Spring Boot application.
It is mainly used for database operations.
Why do we use @Repository?
We use @Repository to:
=> connect with the database
=> save data
=> fetch data
=> update data
=> delete data
It acts as a bridge between the application and the database.
Example
@Repository
public class StudentRepository {
}





















