Skip to main content

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​

AnnotationUsage
@EnableWebSecurityEnables Security config
@EnableMethodSecurityEnables method-level security
@PreAuthorizeCheck BEFORE execution (SpEL)
@PostAuthorizeCheck AFTER execution
@SecuredRequired roles (simple)
@RolesAllowedRequired 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​

AnnotationScopeUsage
@SpringBootTestFull contextIntegration tests
@WebMvcTestWeb layer onlyController tests
@DataJpaTestJPA layer onlyRepository tests
@MockBeanMocked beanReplace a bean
@SpyBeanSpied beanWrap a real bean
@ActiveProfilesProfileChoose test config
@SqlDBLoad 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)
│ │ │ │ │ │
* * * * * *
ExpressionDescription
0 0 * * * *Every hour
0 0 2 * * *Every day at 2 AM
0 0 9-17 * * MON-FRIEvery 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.

AnnotationCondition
@ConditionalOnPropertyProperty has a certain value
@ConditionalOnClassClass present in the classpath
@ConditionalOnMissingClassClass absent from the classpath
@ConditionalOnBeanBean exists in the context
@ConditionalOnMissingBeanBean does not exist in the context
@ConditionalOnExpressionSpEL expression is true
@ConditionalOnWebApplicationApp is a web app
@ConditionalOnNotWebApplicationApp 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​

#AnnotationCategoryRole
1@SpringBootApplicationBootEntry point
2@ComponentCoreGeneric bean
3@ServiceCoreBusiness logic
4@RepositoryCoreDB access
5@ControllerWebMVC controller
6@RestControllerWebREST controller
7@ConfigurationCoreConfig class
8@BeanCoreBean declaration
9@AutowiredCoreInjection
10@QualifierCoreBean choice
11@ValueCoreValue injection
12@ProfileCoreProfile activation
13@ScopeCoreBean scope
14@LazyCoreLazy initialization
15@PostConstructCoreInit after injection
16@PreDestroyCoreCleanup before destruction
17@RequestMappingWebURL mapping
18@GetMappingWebHTTP GET
19@PostMappingWebHTTP POST
20@PutMappingWebHTTP PUT
21@DeleteMappingWebHTTP DELETE
22@PatchMappingWebHTTP PATCH
23@PathVariableWebURL parameter
24@RequestParamWebQuery parameter
25@RequestBodyWebJSON body
26@RequestHeaderWebHTTP header
27@ResponseStatusWebHTTP response code
28@ExceptionHandlerWebException handling
29@RestControllerAdviceWebGlobal error handling
30@CrossOriginWebCORS
31@ValidValidationEnables validation
32@NotNullValidationNot null
33@NotBlankValidationNot empty
34@SizeValidationMin/max size
35@EmailValidationEmail format
36@EntityJPAEntity = table
37@TableJPATable config
38@IdJPAPrimary key
39@GeneratedValueJPAAuto-generate ID
40@ColumnJPAColumn config
41@OneToManyJPA1:N relationship
42@ManyToOneJPAN:1 relationship
43@ManyToManyJPAN:N relationship
44@QueryJPACustom query
45@TransactionalJPATransaction
46@EnableWebSecuritySecuritySecurity config
47@PreAuthorizeSecurityPre-execution authorization
48@SpringBootTestTestIntegration test
49@WebMvcTestTestController test
50@DataJpaTestTestRepository test
51@MockBeanTestBean mock
52@AsyncAdvancedAsynchronous execution
53@ScheduledAdvancedScheduled task
54@CacheableAdvancedCaching
55@EventListenerAdvancedEvent listening

⬅️ Back to Module 17 | ⬅️ Back to Home