Combines @Configuration, @EnableAutoConfiguration, and @ComponentScan. The entry-point annotation for any Spring Boot application.
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}Marks a class as a Spring-managed bean eligible for auto-detection during classpath scanning.
@Component
public class EmailValidator {
public boolean isValid(String email) { ... }
}Specialisation of @Component for the service layer, communicating business logic intent to readers and tools.
@Service
public class UserService {
public User findById(Long id) { ... }
}Specialisation of @Component for DAO classes. Enables Spring to translate persistence exceptions into DataAccessException.
@Repository
public class UserRepository
implements JpaRepository<User, Long> { }Declares a class as a source of @Bean definitions, processed by the Spring container at startup.
@Configuration
public class AppConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}Signals that a method produces a bean to be managed by the Spring container. Used inside @Configuration classes.
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}Injects a bean by type. Can be applied to constructors, fields, or setter methods.
@Service
public class OrderService {
@Autowired
private PaymentService paymentService;
}Disambiguates which bean to inject when multiple candidates of the same type exist in the context.
@Autowired
@Qualifier("smtpMailSender")
private MailSender mailSender;Injects a value from a properties file, environment variable, or SpEL expression into a field or parameter.
@Value("${app.name:MyApp}")
private String appName;
@Value("#{systemProperties['user.timezone']}")
private String timezone;Restricts a bean or configuration to specific active Spring profiles (e.g. dev, prod).
@Configuration
@Profile("dev")
public class DevDataSourceConfig {
@Bean
public DataSource dataSource() { ... }
}Defers bean initialisation until first requested rather than at startup, useful for heavyweight or optional beans.
@Bean
@Lazy
public HeavyReportEngine reportEngine() {
return new HeavyReportEngine();
}Marks a bean as the default candidate when multiple beans of the same type are present and no @Qualifier is specified.
@Bean
@Primary
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}Combines @Controller and @ResponseBody, making every handler method return data serialised to the response body (typically JSON).
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) { ... }
}Marks a class as a Spring MVC controller. Handler methods return view names resolved by a ViewResolver.
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("title", "Home");
return "home";
}
}Maps HTTP requests to handler methods or entire controller classes. Supports method, path, params, headers, and consumes/produces.
@RequestMapping(
value = "/orders",
method = RequestMethod.GET,
produces = "application/json"
)
public List<Order> listOrders() { ... }Shortcut for @RequestMapping(method = RequestMethod.GET). Maps HTTP GET requests.
@GetMapping("/products/{id}")
public ResponseEntity<Product> getProduct(
@PathVariable Long id) { ... }Shortcut for @RequestMapping(method = RequestMethod.POST). Maps HTTP POST requests.
@PostMapping("/users")
public ResponseEntity<User> createUser(
@RequestBody @Valid CreateUserRequest req) { ... }Shortcut for @RequestMapping(method = RequestMethod.PUT). Maps HTTP PUT requests.
@PutMapping("/users/{id}")
public User updateUser(@PathVariable Long id,
@RequestBody UserDTO dto) { ... }Shortcut for @RequestMapping(method = RequestMethod.DELETE). Maps HTTP DELETE requests.
@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(
@PathVariable Long id) { ... }Binds a URI template variable (e.g. /users/{id}) to a method parameter.
@GetMapping("/orders/{orderId}/items/{itemId}")
public Item getItem(
@PathVariable Long orderId,
@PathVariable Long itemId) { ... }Binds a query parameter or form field from the HTTP request to a method parameter.
@GetMapping("/search")
public List<Product> search(
@RequestParam String query,
@RequestParam(defaultValue = "0") int page) { ... }Deserialises the HTTP request body (JSON, XML, etc.) into the method parameter using a registered HttpMessageConverter.
@PostMapping("/checkout")
public Order checkout(
@RequestBody @Valid CartRequest cart) { ... }Sets the HTTP status code returned by a handler method or an exception class.
@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/articles")
public Article create(@RequestBody ArticleDTO dto) { ... }Handles exceptions thrown within a controller. Pair with @ControllerAdvice for global error handling.
@ControllerAdvice
public class GlobalErrorHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleNotFound(
ResourceNotFoundException ex) { ... }
}Enables CORS on a controller or individual handler method, specifying allowed origins, methods, and headers.
@CrossOrigin(origins = "https://app.example.com",
maxAge = 3600)
@RestController
public class ApiController { ... }Marks a class as a JPA entity that is mapped to a database table.
@Entity
@Table(name = "users")
public class User {
@Id @GeneratedValue
private Long id;
private String email;
}Designates a field as the primary key of a JPA entity.
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
}Customises the mapping between an entity field and its database column (name, nullability, length, etc.).
@Column(name = "email_address",
nullable = false,
unique = true,
length = 255)
private String email;Wraps a method (or all methods in a class) in a database transaction. Supports rollback rules, propagation, and isolation levels.
@Service
public class TransferService {
@Transactional(rollbackFor = Exception.class)
public void transfer(Long from, Long to, BigDecimal amount) {
debit(from, amount);
credit(to, amount);
}
}Defines a one-to-many relationship between entities, typically used with mappedBy to specify the owning side.
@Entity
public class Order {
@OneToMany(mappedBy = "order",
cascade = CascadeType.ALL,
orphanRemoval = true)
private List<OrderItem> items = new ArrayList<>();
}Defines a many-to-one relationship. The annotated entity holds the foreign key column.
@Entity
public class OrderItem {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "order_id", nullable = false)
private Order order;
}Declares a custom JPQL or native SQL query directly on a Spring Data repository method.
@Query("SELECT u FROM User u WHERE u.email = :email AND u.active = true")
Optional<User> findActiveByEmail(@Param("email") String email);Enables Spring Data JPA repositories, allowing Spring to scan and create repository beans automatically.
@Configuration
@EnableJpaRepositories(basePackages = "com.example.repo")
public class JpaConfig { ... }Activates Spring Security's web security support, triggering the creation of the SpringSecurityFilterChain.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http)
throws Exception { ... }
}Evaluates a SpEL expression before entering a method and throws an AccessDeniedException if it returns false.
@PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.id")
public User getUser(Long userId) { ... }Evaluates a SpEL expression after a method completes, allowing access checks against the return value.
@PostAuthorize("returnObject.owner == authentication.name")
public Document getDocument(Long id) { ... }Restricts access to a method based on one or more role strings. A simpler alternative to @PreAuthorize.
@Secured({"ROLE_ADMIN", "ROLE_SUPERUSER"})
public void deleteUser(Long userId) { ... }Enables Spring Security method-level annotations (@PreAuthorize, @PostAuthorize, @Secured) on a configuration class.
@Configuration
@EnableMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig { }Marks a class as an AOP aspect containing advice (before, after, around) and pointcut declarations.
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint jp) {
log.info("Calling: {}", jp.getSignature());
}
}Wraps the target method, allowing code to run before and after the join point and the ability to alter return values.
@Around("@annotation(com.example.Timed)")
public Object measureTime(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
Object result = pjp.proceed();
log.info("Elapsed: {}ms", System.currentTimeMillis() - start);
return result;
}Runs advice before the matched join point executes. Cannot prevent the target method from proceeding.
@Before("@annotation(RequiresAudit)")
public void auditEntry(JoinPoint jp) {
auditLog.record(jp.getSignature().getName());
}Runs advice after the matched join point has finished (regardless of success or exception).
@After("execution(* com.example.repo.*.*(..))")
public void afterRepoCall(JoinPoint jp) {
metricsRegistry.increment("db.calls");
}Enables support for handling @Aspect beans using AspectJ's auto-proxying mechanism.
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AopConfig { }Activates Spring's scheduled task execution capability, enabling @Scheduled annotations to be processed.
@SpringBootApplication
@EnableScheduling
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}Marks a method to be executed on a fixed-rate, fixed-delay, or cron expression schedule.
@Scheduled(cron = "0 0 2 * * MON-FRI")
public void generateNightlyReport() {
reportService.generate();
}
@Scheduled(fixedDelay = 5000)
public void pollExternalApi() { ... }Runs a method in a separate thread (from a task executor pool) instead of the caller's thread. Requires @EnableAsync.
@Async
public CompletableFuture<Report> buildReport(Long id) {
// runs on a thread-pool thread
return CompletableFuture.completedFuture(doWork(id));
}Enables Spring's asynchronous method execution support so that @Async annotations are honoured.
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor exec = new ThreadPoolTaskExecutor();
exec.setCorePoolSize(4);
exec.initialize();
return exec;
}
}Bootstraps the full Spring application context for integration tests. Supports webEnvironment settings.
@SpringBootTest(webEnvironment =
SpringBootTest.WebEnvironment.RANDOM_PORT)
class OrderApiIT {
@Autowired TestRestTemplate rest;
@Test
void createOrder_returns201() { ... }
}Creates a slice test context containing only Spring MVC components. Fast alternative to @SpringBootTest for controller tests.
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired MockMvc mvc;
@MockBean UserService userService;
@Test
void getUser_returns200() throws Exception {
mvc.perform(get("/api/users/1"))
.andExpect(status().isOk());
}
}Configures an in-memory database and JPA-specific components for testing repositories without loading the full context.
@DataJpaTest
class UserRepositoryTest {
@Autowired UserRepository repo;
@Test
void findByEmail_returnsUser() {
repo.save(new User("bob@example.com"));
assertThat(repo.findByEmail("bob@example.com")).isPresent();
}
}Adds a Mockito mock into the Spring application context, replacing any existing bean of the same type.
@WebMvcTest(CheckoutController.class)
class CheckoutControllerTest {
@MockBean PaymentService paymentService;
@Test
void checkout_callsPayment() { ... }
}Overrides application properties for a specific test class, useful for pointing at test-specific config files.
@SpringBootTest
@TestPropertySource(properties = {
"spring.datasource.url=jdbc:h2:mem:testdb",
"feature.flag.new-ui=true"
})
class FeatureFlagTest { ... }