Spring Annotations
All Java Topics
Last updated: May 25, 2026
Author: ManaCoding Team
Spring annotations are metadata used to simplify configuration in Spring Framework. They replace XML configuration and help define beans, dependency injection, and application behavior.
Syntax
@Component
class MyClass {}
@Autowired
private MyClass obj;
Example Program
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Component
class Engine {
public String start() {
return "Engine Started";
}
}
@Service
class CarService {
@Autowired
private Engine engine;
public String runCar() {
return engine.start();
}
}
@RestController
class CarController {
@Autowired
private CarService service;
@GetMapping("/car")
public String getCarStatus() {
return service.runCar();
}
}
// Output (API response):
// Engine Started
What are Spring Annotations?
- 1 Metadata used in Spring applications.
- 2 Replace XML configuration.
- 3 Used for dependency injection.
- 4 Simplify development.
Common Spring Annotations
- 1 @Component – generic bean
- 2 @Service – business logic layer
- 3 @Repository – database layer
- 4 @Controller – MVC controller
- 5 @RestController – REST APIs
- 6 @Autowired – dependency injection
- 7 @Configuration – configuration class
- 8 @Bean – custom bean definition
How Annotations Work
- 1 Spring scans annotated classes.
- 2 Creates beans automatically.
- 3 Injects dependencies.
- 4 Manages lifecycle of objects.
Why Use Annotations?
- 1 Reduces boilerplate code.
- 2 Simplifies configuration.
- 3 Improves readability.
- 4 Faster development.
Quick Summary
- Spring annotations simplify configuration.
- Used for bean creation and dependency injection.
- Common ones include @Component, @Service, @Autowired.
- Core part of Spring Boot development.
FAQs
What are Spring annotations?
Metadata used to configure Spring applications without XML.
What is @Autowired used for?
It is used for dependency injection.
Difference between @Component and @Service?
@Component is generic, @Service is for business logic layer.
What is @RestController?
It is used to create REST APIs in Spring Boot.
Why use annotations in Spring?
To reduce configuration and improve readability.
Interview Questions
Q1.
What are Spring annotations?
Answer:
Metadata used to configure Spring applications without XML.
Q2.
What is @Autowired used for?
Answer:
It is used for dependency injection.
Q3.
Difference between @Component and @Service?
Answer:
@Component is generic, @Service is for business logic layer.
Q4.
What is @RestController?
Answer:
It is used to create REST APIs in Spring Boot.
Q5.
Why use annotations in Spring?
Answer:
To reduce configuration and improve readability.
Quiz
Which annotation is used for REST APIs in Spring Boot?