liminfo

Spring Reference

Free reference guide: Spring Reference

26 results

About Spring Reference

The Spring Framework Reference is a searchable quick-reference for Java enterprise application development with Spring. It covers component stereotypes (@Component, @Service, @Repository, @Controller, @Configuration) and dependency injection patterns including @Autowired field injection, constructor injection (the recommended approach), @Qualifier for disambiguating beans, @Value for property binding, and @Bean method definitions. Each entry provides production Java code examples following current Spring best practices.

This reference organizes Spring concepts into six categories: Components, Dependency Injection, AOP, MVC, Security, and Data. The AOP section covers aspect-oriented programming with @Aspect, @Before/@After advice, @Around for cross-cutting concerns like timing, and @Transactional for declarative transaction management. The MVC section details request mapping annotations (@GetMapping, @PostMapping), parameter binding (@RequestBody, @PathVariable, @RequestParam), and @ExceptionHandler for centralized error handling.

The Security and Data sections address two of Spring's most powerful modules. Spring Security entries demonstrate SecurityFilterChain configuration for URL-based authorization and @PreAuthorize for method-level access control with SpEL expressions. Spring Data JPA entries cover JpaRepository interface with derived query methods (findByEmail, findByUsername), @Query for custom JPQL, @Entity mapping with @Id and @GeneratedValue, and Pageable for automatic pagination handling in REST endpoints.

Key Features

  • Component stereotype annotations (@Component, @Service, @Repository, @Controller, @Configuration) with usage context
  • Dependency injection patterns: constructor injection, @Autowired, @Qualifier, @Value, and @Bean definitions
  • AOP aspects with @Before, @After, @Around advice and @Transactional declarative transaction management
  • Spring MVC request mapping with @GetMapping, @PostMapping, @RequestBody, @PathVariable, and @RequestParam
  • @ExceptionHandler for centralized error handling with ResponseEntity and HTTP status codes
  • Spring Security with SecurityFilterChain URL authorization and @PreAuthorize method-level checks
  • Spring Data JPA with JpaRepository, derived query methods, @Query JPQL, and Pageable pagination
  • @Entity JPA mapping with @Id, @GeneratedValue, @Table, and relationship annotations

Frequently Asked Questions

Why is constructor injection preferred over @Autowired field injection?

Constructor injection makes dependencies explicit, ensures immutability with final fields, and guarantees the object is fully initialized. It prevents NullPointerException from partially constructed objects and makes unit testing easier since you can pass mock dependencies directly. Since Spring 4.3, a single constructor does not even need @Autowired. Field injection hides dependencies and makes it harder to identify when a class has too many responsibilities.

What is the difference between @Component, @Service, @Repository, and @Controller?

All four register a class as a Spring bean, but they serve different semantic roles. @Component is the generic stereotype. @Service marks service layer classes (business logic). @Repository marks data access classes and adds automatic exception translation for persistence exceptions. @Controller marks web controllers for handling HTTP requests. Using the correct stereotype improves code readability and enables targeted AOP advice.

How does @Transactional work in Spring?

@Transactional creates a proxy around the annotated method that begins a transaction before execution and commits after completion. If a runtime exception is thrown, the transaction rolls back. Key attributes include propagation (REQUIRED, REQUIRES_NEW), isolation level, readOnly flag for query optimization, and rollbackFor to specify which exceptions trigger rollback. Note that @Transactional only works on public methods called from outside the class due to proxy-based AOP.

How do I handle exceptions globally in Spring MVC?

Use @ControllerAdvice (or @RestControllerAdvice) with @ExceptionHandler methods. Each handler method catches a specific exception type and returns a ResponseEntity with an appropriate HTTP status code and error body. This centralizes error handling across all controllers. You can also use @ResponseStatus on custom exception classes. For validation errors, handle MethodArgumentNotValidException to return field-level error messages.

What is the SecurityFilterChain and how does it replace WebSecurityConfigurerAdapter?

Since Spring Security 5.7, SecurityFilterChain is a @Bean that replaces the deprecated WebSecurityConfigurerAdapter. You configure it by chaining methods on HttpSecurity: authorizeHttpRequests() for URL patterns, formLogin()/httpBasic() for authentication, csrf() for CSRF protection, and cors() for cross-origin settings. Multiple SecurityFilterChain beans can be defined with @Order for different URL patterns, providing more flexible and composable security configuration.

How do derived query methods work in Spring Data JPA?

Spring Data JPA automatically implements query methods based on method name conventions. For example, findByEmail(String email) generates "SELECT ... WHERE email = ?". You can combine properties with And/Or (findByNameAndAge), use keywords like OrderBy, Between, LessThan, Like, and In, and return Optional, List, Page, or Stream types. For complex queries beyond naming conventions, use @Query with JPQL or native SQL.

What does @PreAuthorize do and how do I use SpEL in it?

@PreAuthorize evaluates a Spring Expression Language (SpEL) expression before method execution. Common expressions include hasRole("ADMIN"), hasAuthority("WRITE"), isAuthenticated(), and #username == authentication.principal.username for resource ownership checks. Enable it with @EnableMethodSecurity. It is more flexible than URL-based security because it can access method parameters and supports complex boolean logic.

How does Pageable work for API pagination in Spring Data?

Add a Pageable parameter to your controller method and repository. Spring automatically extracts page, size, and sort parameters from the request query string (e.g., ?page=0&size=20&sort=name,asc). The repository method returns a Page<T> object containing the data slice plus total count, total pages, and navigation metadata. Default page size can be configured with @PageableDefault or in application.properties with spring.data.web.pageable.default-page-size.