A comprehensive reference and cheatsheet for commonly used Spring and Spring Boot annotations. Includes detailed explanations, use cases, and examples for quick learning and practical implementation.
| Annotation | Purpose |
|---|---|
@Autowired |
Injects dependencies automatically |
@Profile |
Activates beans based on environment profile |
@Component |
Generic component scan target |
@Service |
Business logic layer component |
@Repository |
Data access component with exception translation |
@Controller |
Web layer component (non-REST) |
@RestController |
Combines @Controller + @ResponseBody |
@Configuration |
Bean definition source |
@Bean |
Declares a bean managed by Spring |
@Qualifier |
Disambiguates multiple beans of same type |
@Value |
Injects values from properties/environment |
- Purpose: Declares a method that produces a bean managed by the Spring IoC container.
- Example:
@Configuration
public class AppConfig {
@Bean
public Dog dog() {
return new Dog("Tommy");
}
}@Component– Generic Spring-managed component.@Service– Marks business logic layer beans.@Repository– DAO layer bean, auto-translates exceptions.@Controller– MVC controller for handling HTTP requests.@RestController–@Controller+@ResponseBody, returns JSON/XML directly.
Example:
@Service
public class CarService {
public String getCarName() {
return "Tesla Model 3";
}
}
@RestController
public class CarController {
@Autowired
private CarService carService;
@GetMapping("/car")
public String car() {
return carService.getCarName();
}
}- Marks a class as a configuration class, defining beans.
- Often used with
@Bean.
Executed after dependency injection, for initialization.
@Component
public class InitExample {
@PostConstruct
public void init() {
System.out.println("Bean initialized!");
}
}Executed before bean destruction, often for cleanup.
@Component
public class DestroyExample {
@PreDestroy
public void cleanup() {
System.out.println("Bean destroyed!");
}
}@Import– Import another config class.@PropertySource– Load properties from file.@Value– Inject values from properties/env.@ComponentScan– Configure package scanning.
Example:
@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
@Value("${app.name}")
private String appName;
@Bean
public String printAppName() {
return appName;
}
}@Lazy– Lazy initialization.@Profile– Activate beans per environment.@Scope– Define bean scope (singleton, prototype).@DependsOn– Create dependency order.@Order– Sorting order of beans.@Primary– Preferred bean if multiple candidates.@Conditional– Create beans conditionally.
Injects dependencies.
@Component
public class Car {
@Autowired
private Engine engine;
}Disambiguates multiple beans.
@Component("petrolEngine")
class PetrolEngine implements Engine {}
@Component("dieselEngine")
class DieselEngine implements Engine {}
@Component
class Car {
@Autowired
@Qualifier("dieselEngine")
private Engine engine;
}@Valid– Apply validation rules.@NotNull,@NotEmpty,@NotBlank– Field constraints.@Past,@Future– Date/time constraints.
Example:
@PostMapping("/addUser")
public ResponseEntity<String> addUser(@Valid @RequestBody User user) {
return ResponseEntity.ok("User added");
}@SpringBootApplication– Combines@Configuration,@EnableAutoConfiguration,@ComponentScan.@EnableAutoConfiguration– Enables Spring Boot’s auto-configuration.@ConfigurationProperties– Binds external properties.
Example:
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}@SpringBootTest– Full application context.@WebMvcTest– Web layer only.@DataJpaTest– JPA components.@MockBean– Mock bean.
Example:
@SpringBootTest
class CarServiceTest {
@Autowired
private CarService carService;
@Test
void testCarName() {
assertEquals("Tesla Model 3", carService.getCarName());
}
}@Entity,@Table,@Id,@GeneratedValue– Entity mapping.@ManyToOne,@OneToOne,@ManyToMany,@JoinColumn,@JoinTable– Relationships.@CreationTimestamp,@UpdateTimestamp– Auto timestamps.
Example:
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "user")
private List<Order> orders;
}@EnableWebSecurity– Enable Spring Security.@PreAuthorize,@PostAuthorize– Method-level security.@Secured,@RolesAllowed– Role-based access.
Example:
@RestController
public class AdminController {
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin")
public String adminOnly() {
return "Admin content";
}
}@Aspect– Define aspect class.@Before,@After,@Around– Define advices.@EnableAspectJAutoProxy– Enable proxy-based AOP.
Example:
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Method called: " + joinPoint.getSignature());
}
}- Spring Framework Documentation
- Baeldung Spring Tutorials
- Spring in Action (Book)
🚀 This guide now covers all major annotations with detailed explanations + code examples for real-world usage.