Chapter 4: Security, Test, and Advanced Annotations
1. Spring Security Annotations
@EnableWebSecurity
Enables custom security configuration.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.build();
}
}
@EnableMethodSecurity
Enables method-level security.
@Configuration
@EnableMethodSecurity // Enables @PreAuthorize, @PostAuthorize, @Secured
public class MethodSecurityConfig {
}
@PreAuthorize
Checks permissions before method execution.
@RestController
@RequestMapping("/api/admin")
public class AdminController {
@GetMapping("/users")
@PreAuthorize("hasRole('ADMIN')")
public List<User> getAllUsers() { ... }
@GetMapping("/stats")
@PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')")
public Stats getStats() { ... }
@DeleteMapping("/users/{id}")
@PreAuthorize("hasRole('ADMIN') and #id != principal.id")
public void deleteUser(@PathVariable Long id) { ... }
@GetMapping("/users/{id}")
@PreAuthorize("#id == principal.id or hasRole('ADMIN')")
public User getUser(@PathVariable Long id) { ... }
@PreAuthorize("isAuthenticated()")
@GetMapping("/profile")
public User getProfile() { ... }
}
@PostAuthorize
Checks permissions after execution.
@GetMapping("/{id}")
@PostAuthorize("returnObject.owner == authentication.name or hasRole('ADMIN')")
public Document getDocument(@PathVariable Long id) {
return documentService.findById(id);
}
@Secured
Specifies required roles (simpler than @PreAuthorize).
@Secured("ROLE_ADMIN")
public void adminOnly() { ... }
@Secured({"ROLE_ADMIN", "ROLE_MANAGER"})
public void adminOrManager() { ... }
@RolesAllowed
JSR-250 standard, similar to @Secured.
@RolesAllowed("ADMIN")
public void adminOnly() { ... }
Security Summary
| Annotation | Usage |
|---|---|
@EnableWebSecurity | Enables Security config |
@EnableMethodSecurity | Enables method-level security |
@PreAuthorize | Check BEFORE execution (SpEL) |
@PostAuthorize | Check AFTER execution |
@Secured | Required roles (simple) |
@RolesAllowed | Required roles (JSR-250) |
2. Test Annotations
@SpringBootTest
Loads the full Spring context for integration tests.
@SpringBootTest
class UserServiceIntegrationTest {
@Autowired
private UserService userService;
@Test
void shouldCreateUser() {
User user = userService.create(new UserDto("Jean", "jean@test.com"));
assertThat(user.getId()).isNotNull();
}
}
// With a random web server
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ApiIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
void shouldReturnProducts() {
ResponseEntity<List> response = restTemplate.getForEntity("/api/products", List.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
}
@WebMvcTest
Tests only the controller layer (no DB, no real services).
@WebMvcTest(ProductController.class)
class ProductControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private ProductService productService;
@Test
void shouldReturnProducts() throws Exception {
when(productService.findAll()).thenReturn(List.of(new Product("Laptop", 999.99)));
mockMvc.perform(get("/api/products"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].name").value("Laptop"));
}
}
@DataJpaTest
Tests only the JPA persistence layer.
@DataJpaTest
class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
@Autowired
private TestEntityManager entityManager;
@Test
void shouldFindByEmail() {
entityManager.persistAndFlush(new User("Jean", "jean@test.com"));
Optional<User> found = userRepository.findByEmail("jean@test.com");
assertThat(found).isPresent();
assertThat(found.get().getName()).isEqualTo("Jean");
}
}
@MockBean
Replaces a Spring bean with a Mockito mock.
@WebMvcTest(UserController.class)
class UserControllerTest {
@MockBean
private UserService userService; // Mock instead of the real service
@Test
void shouldReturnUser() {
when(userService.findById(1L)).thenReturn(new User("Jean"));
// ...
}
}
@SpyBean
Wraps a real bean with a Mockito spy (real calls except stubbed ones).
@SpringBootTest
class NotificationTest {
@SpyBean
private EmailService emailService;
@Test
void shouldSendEmail() {
doNothing().when(emailService).sendEmail(anyString(), anyString());
// The rest of the methods call the real code
}
}
@TestConfiguration
Provides test-specific configuration.
@TestConfiguration
public class TestSecurityConfig {
@Bean
public SecurityFilterChain testFilterChain(HttpSecurity http) throws Exception {
return http.csrf(c -> c.disable())
.authorizeHttpRequests(a -> a.anyRequest().permitAll())
.build();
}
}
@ActiveProfiles
Activates a specific Spring profile for testing.
@SpringBootTest
@ActiveProfiles("test")
class ServiceTest {
// Uses application-test.yml
}
@Sql / @SqlGroup
Executes SQL scripts before/after a test.
@DataJpaTest
@Sql("/test-data.sql")
class ProductRepositoryTest {
// test-data.sql is executed before each test
}
@Sql(scripts = "/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
Test Summary
| Annotation | Scope | Usage |
|---|---|---|
@SpringBootTest | Full context | Integration tests |
@WebMvcTest | Web layer only | Controller tests |
@DataJpaTest | JPA layer only | Repository tests |
@MockBean | Mocked bean | Replace a bean |
@SpyBean | Spied bean | Wrap a real bean |
@ActiveProfiles | Profile | Choose test config |
@Sql | DB | Load SQL data |
3. Asynchronous and Scheduling Annotations
@EnableAsync / @Async
Executes a method asynchronously (in a separate thread).
@Configuration
@EnableAsync
public class AsyncConfig {
}
@Service
public class EmailService {
@Async
public CompletableFuture<String> sendEmailAsync(String to, String body) {
// Executed in a separate thread
// ... send email
return CompletableFuture.completedFuture("Email sent to " + to);
}
}
@EnableScheduling / @Scheduled
Schedules periodic execution of a method.
@Configuration
@EnableScheduling
public class SchedulingConfig {
}
@Service
public class CleanupService {
@Scheduled(fixedRate = 60000) // Every 60 seconds
public void cleanupExpiredTokens() {
tokenRepository.deleteExpired();
}
@Scheduled(fixedDelay = 30000) // 30 seconds after the previous execution ends
public void processQueue() {
queueService.processNext();
}
@Scheduled(cron = "0 0 2 * * ?") // Every day at 2 AM
public void dailyReport() {
reportService.generateDailyReport();
}
@Scheduled(cron = "0 0 * * * MON-FRI") // Every hour, Monday to Friday
public void hourlySync() {
syncService.sync();
}
}
Cron Syntax
┌───────── second (0-59)
│ ┌─────── minute (0-59)
│ │ ┌───── hour (0-23)
│ │ │ ┌─── day of month (1-31)
│ │ │ │ ┌─ month (1-12)
│ │ │ │ │ ┌ day of week (0-7, MON-SUN)
│ │ │ │ │ │
* * * * * *
| Expression | Description |
|---|---|
0 0 * * * * | Every hour |
0 0 2 * * * | Every day at 2 AM |
0 0 9-17 * * MON-FRI | Every hour from 9 AM to 5 PM on weekdays |
0 */15 * * * * | Every 15 minutes |
0 0 0 1 * * | The first of every month at midnight |
4. Cache Annotations
@EnableCaching / @Cacheable / @CacheEvict / @CachePut
@Configuration
@EnableCaching
public class CacheConfig {
}
@Service
public class ProductService {
@Cacheable(value = "products", key = "#id")
public Product findById(Long id) {
// Result cached; subsequent calls do not hit the DB
return productRepository.findById(id).orElseThrow();
}
@Cacheable(value = "productList", unless = "#result.size() == 0")
public List<Product> findAll() {
return productRepository.findAll();
}
@CachePut(value = "products", key = "#product.id")
public Product update(Product product) {
// Updates the cache with the new result
return productRepository.save(product);
}
@CacheEvict(value = "products", key = "#id")
public void delete(Long id) {
// Removes the entry from the cache
productRepository.deleteById(id);
}
@CacheEvict(value = "products", allEntries = true)
public void clearCache() {
// Clears the entire "products" cache
}
}
5. AOP (Aspect-Oriented Programming) Annotations
@Aspect / @Before / @After / @Around
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
log.info("Calling: {}", joinPoint.getSignature().getName());
}
@After("execution(* com.example.service.*.*(..))")
public void logAfter(JoinPoint joinPoint) {
log.info("Finished: {}", joinPoint.getSignature().getName());
}
@Around("@annotation(com.example.annotation.Timed)")
public Object measureTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long duration = System.currentTimeMillis() - start;
log.info("{} executed in {} ms", joinPoint.getSignature().getName(), duration);
return result;
}
}
6. Spring Boot Auto-Configuration Annotations
@EnableAutoConfiguration
Included in @SpringBootApplication. Enables auto-configuration based on dependencies.
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
// Disables DataSource auto-configuration
@ConditionalOn...
Family of annotations for conditional configuration.
| Annotation | Condition |
|---|---|
@ConditionalOnProperty | Property has a certain value |
@ConditionalOnClass | Class present in the classpath |
@ConditionalOnMissingClass | Class absent from the classpath |
@ConditionalOnBean | Bean exists in the context |
@ConditionalOnMissingBean | Bean does not exist in the context |
@ConditionalOnExpression | SpEL expression is true |
@ConditionalOnWebApplication | App is a web app |
@ConditionalOnNotWebApplication | App is not a web app |
7. Messaging and Events Annotations
@EventListener
Listens to Spring events.
@Component
public class UserEventListener {
@EventListener
public void handleUserCreated(UserCreatedEvent event) {
log.info("New user: {}", event.getUser().getEmail());
emailService.sendWelcomeEmail(event.getUser());
}
@Async
@EventListener
public void handleUserCreatedAsync(UserCreatedEvent event) {
// Processed asynchronously
}
}
@TransactionalEventListener
Listens to transaction-bound events.
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void handleAfterCommit(OrderCreatedEvent event) {
// Executed only if the transaction succeeded
notificationService.notifyNewOrder(event.getOrder());
}
8. REST Client Annotations
@FeignClient (Spring Cloud)
Declares a declarative REST client.
@FeignClient(name = "user-service", url = "http://localhost:8081")
public interface UserClient {
@GetMapping("/api/users/{id}")
UserDto getUser(@PathVariable Long id);
@PostMapping("/api/users")
UserDto createUser(@RequestBody CreateUserDto dto);
}
Global Summary Table
The 50+ most used annotations
| # | Annotation | Category | Role |
|---|---|---|---|
| 1 | @SpringBootApplication | Boot | Entry point |
| 2 | @Component | Core | Generic bean |
| 3 | @Service | Core | Business logic |
| 4 | @Repository | Core | DB access |
| 5 | @Controller | Web | MVC controller |
| 6 | @RestController | Web | REST controller |
| 7 | @Configuration | Core | Config class |
| 8 | @Bean | Core | Bean declaration |
| 9 | @Autowired | Core | Injection |
| 10 | @Qualifier | Core | Bean choice |
| 11 | @Value | Core | Value injection |
| 12 | @Profile | Core | Profile activation |
| 13 | @Scope | Core | Bean scope |
| 14 | @Lazy | Core | Lazy initialization |
| 15 | @PostConstruct | Core | Init after injection |
| 16 | @PreDestroy | Core | Cleanup before destruction |
| 17 | @RequestMapping | Web | URL mapping |
| 18 | @GetMapping | Web | HTTP GET |
| 19 | @PostMapping | Web | HTTP POST |
| 20 | @PutMapping | Web | HTTP PUT |
| 21 | @DeleteMapping | Web | HTTP DELETE |
| 22 | @PatchMapping | Web | HTTP PATCH |
| 23 | @PathVariable | Web | URL parameter |
| 24 | @RequestParam | Web | Query parameter |
| 25 | @RequestBody | Web | JSON body |
| 26 | @RequestHeader | Web | HTTP header |
| 27 | @ResponseStatus | Web | HTTP response code |
| 28 | @ExceptionHandler | Web | Exception handling |
| 29 | @RestControllerAdvice | Web | Global error handling |
| 30 | @CrossOrigin | Web | CORS |
| 31 | @Valid | Validation | Enables validation |
| 32 | @NotNull | Validation | Not null |
| 33 | @NotBlank | Validation | Not empty |
| 34 | @Size | Validation | Min/max size |
| 35 | @Email | Validation | Email format |
| 36 | @Entity | JPA | Entity = table |
| 37 | @Table | JPA | Table config |
| 38 | @Id | JPA | Primary key |
| 39 | @GeneratedValue | JPA | Auto-generate ID |
| 40 | @Column | JPA | Column config |
| 41 | @OneToMany | JPA | 1:N relationship |
| 42 | @ManyToOne | JPA | N:1 relationship |
| 43 | @ManyToMany | JPA | N:N relationship |
| 44 | @Query | JPA | Custom query |
| 45 | @Transactional | JPA | Transaction |
| 46 | @EnableWebSecurity | Security | Security config |
| 47 | @PreAuthorize | Security | Pre-execution authorization |
| 48 | @SpringBootTest | Test | Integration test |
| 49 | @WebMvcTest | Test | Controller test |
| 50 | @DataJpaTest | Test | Repository test |
| 51 | @MockBean | Test | Bean mock |
| 52 | @Async | Advanced | Asynchronous execution |
| 53 | @Scheduled | Advanced | Scheduled task |
| 54 | @Cacheable | Advanced | Caching |
| 55 | @EventListener | Advanced | Event listening |