Chapitre 4: Annotations Security, Test et Avancées
1. Annotations Spring Security
@EnableWebSecurity
Active la configuration de sécurité personnalisée.
@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
Active la sécurité au niveau des méthodes.
@Configuration
@EnableMethodSecurity // Active @PreAuthorize, @PostAuthorize, @Secured
public class MethodSecurityConfig {
}
@PreAuthorize
Vérifie les autorisations avant l'exécution de la méthode.
@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
Vérifie les autorisations après l'exécution.
@GetMapping("/{id}")
@PostAuthorize("returnObject.owner == authentication.name or hasRole('ADMIN')")
public Document getDocument(@PathVariable Long id) {
return documentService.findById(id);
}
@Secured
Spécifie les rôles requis (plus simple que @PreAuthorize).
@Secured("ROLE_ADMIN")
public void adminOnly() { ... }
@Secured({"ROLE_ADMIN", "ROLE_MANAGER"})
public void adminOrManager() { ... }
@RolesAllowed
Standard JSR-250, similaire à @Secured.
@RolesAllowed("ADMIN")
public void adminOnly() { ... }
Résumé Security
| Annotation | Usage |
|---|---|
@EnableWebSecurity | Active la config Security |
@EnableMethodSecurity | Active la sécurité par méthode |
@PreAuthorize | Vérification AVANT exécution (SpEL) |
@PostAuthorize | Vérification APRÈS exécution |
@Secured | Rôles requis (simple) |
@RolesAllowed | Rôles requis (JSR-250) |
2. Annotations de Test
@SpringBootTest
Charge le contexte Spring complet pour les tests d'intégration.
@SpringBootTest
class UserServiceIntegrationTest {
@Autowired
private UserService userService;
@Test
void shouldCreateUser() {
User user = userService.create(new UserDto("Jean", "jean@test.com"));
assertThat(user.getId()).isNotNull();
}
}
// Avec un serveur web aléatoire
@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
Teste uniquement la couche contrôleur (pas de BDD, pas de services réels).
@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
Teste uniquement la couche de persistance JPA.
@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
Remplace un bean Spring par un mock Mockito.
@WebMvcTest(UserController.class)
class UserControllerTest {
@MockBean
private UserService userService; // Mock au lieu du vrai service
@Test
void shouldReturnUser() {
when(userService.findById(1L)).thenReturn(new User("Jean"));
// ...
}
}
@SpyBean
Enveloppe un vrai bean avec un spy Mockito (appels réels sauf ceux stubés).
@SpringBootTest
class NotificationTest {
@SpyBean
private EmailService emailService;
@Test
void shouldSendEmail() {
doNothing().when(emailService).sendEmail(anyString(), anyString());
// Le reste des méthodes appelle le vrai code
}
}
@TestConfiguration
Fournit une configuration spécifique aux tests.
@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
Active un profil Spring spécifique pour le test.
@SpringBootTest
@ActiveProfiles("test")
class ServiceTest {
// Utilise application-test.yml
}
@Sql / @SqlGroup
Exécute des scripts SQL avant/après un test.
@DataJpaTest
@Sql("/test-data.sql")
class ProductRepositoryTest {
// test-data.sql est exécuté avant chaque test
}
@Sql(scripts = "/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
Résumé Test
| Annotation | Portée | Usage |
|---|---|---|
@SpringBootTest | Contexte complet | Tests d'intégration |
@WebMvcTest | Couche Web seule | Tests de contrôleurs |
@DataJpaTest | Couche JPA seule | Tests de repositories |
@MockBean | Bean mocké | Remplacer un bean |
@SpyBean | Bean espionné | Wrapper un vrai bean |
@ActiveProfiles | Profil | Choisir la config test |
@Sql | BDD | Charger des données SQL |
3. Annotations Asynchrone et Planification
@EnableAsync / @Async
Exécute une méthode de manière asynchrone (dans un thread séparé).
@Configuration
@EnableAsync
public class AsyncConfig {
}
@Service
public class EmailService {
@Async
public CompletableFuture<String> sendEmailAsync(String to, String body) {
// Exécuté dans un thread séparé
// ... envoi email
return CompletableFuture.completedFuture("Email envoyé à " + to);
}
}
@EnableScheduling / @Scheduled
Planifie l'exécution périodique d'une méthode.
@Configuration
@EnableScheduling
public class SchedulingConfig {
}
@Service
public class CleanupService {
@Scheduled(fixedRate = 60000) // Toutes les 60 secondes
public void cleanupExpiredTokens() {
tokenRepository.deleteExpired();
}
@Scheduled(fixedDelay = 30000) // 30 secondes après la fin de l'exécution précédente
public void processQueue() {
queueService.processNext();
}
@Scheduled(cron = "0 0 2 * * ?") // Tous les jours à 2h du matin
public void dailyReport() {
reportService.generateDailyReport();
}
@Scheduled(cron = "0 0 * * * MON-FRI") // Chaque heure, lundi au vendredi
public void hourlySync() {
syncService.sync();
}
}
Syntaxe Cron
┌───────── seconde (0-59)
│ ┌─────── minute (0-59)
│ │ ┌───── heure (0-23)
│ │ │ ┌─── jour du mois (1-31)
│ │ │ │ ┌─ mois (1-12)
│ │ │ │ │ ┌ jour de la semaine (0-7, MON-SUN)
│ │ │ │ │ │
* * * * * *
| Expression | Description |
|---|---|
0 0 * * * * | Chaque heure |
0 0 2 * * * | Tous les jours à 2h |
0 0 9-17 * * MON-FRI | Chaque heure de 9h à 17h en semaine |
0 */15 * * * * | Toutes les 15 minutes |
0 0 0 1 * * | Le premier de chaque mois à minuit |
4. Annotations de Cache
@EnableCaching / @Cacheable / @CacheEvict / @CachePut
@Configuration
@EnableCaching
public class CacheConfig {
}
@Service
public class ProductService {
@Cacheable(value = "products", key = "#id")
public Product findById(Long id) {
// Résultat mis en cache ; les appels suivants ne touchent pas la BDD
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) {
// Met à jour le cache avec le nouveau résultat
return productRepository.save(product);
}
@CacheEvict(value = "products", key = "#id")
public void delete(Long id) {
// Supprime l'entrée du cache
productRepository.deleteById(id);
}
@CacheEvict(value = "products", allEntries = true)
public void clearCache() {
// Vide tout le cache "products"
}
}
5. Annotations AOP (Programmation Orientée Aspect)
@Aspect / @Before / @After / @Around
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
log.info("Appel: {}", joinPoint.getSignature().getName());
}
@After("execution(* com.example.service.*.*(..))")
public void logAfter(JoinPoint joinPoint) {
log.info("Fin: {}", 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("{} exécuté en {} ms", joinPoint.getSignature().getName(), duration);
return result;
}
}
6. Annotations Spring Boot Auto-Configuration
@EnableAutoConfiguration
Inclus dans @SpringBootApplication. Active la configuration automatique basée sur les dépendances.
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
// Désactive l'auto-configuration de la DataSource
@ConditionalOn...
Famille d'annotations pour la configuration conditionnelle.
| Annotation | Condition |
|---|---|
@ConditionalOnProperty | Propriété a une certaine valeur |
@ConditionalOnClass | Classe présente dans le classpath |
@ConditionalOnMissingClass | Classe absente du classpath |
@ConditionalOnBean | Bean existe dans le contexte |
@ConditionalOnMissingBean | Bean n'existe pas dans le contexte |
@ConditionalOnExpression | Expression SpEL est vraie |
@ConditionalOnWebApplication | L'app est une app web |
@ConditionalOnNotWebApplication | L'app n'est pas une app web |
7. Annotations de Messaging et Events
@EventListener
Écoute les événements Spring.
@Component
public class UserEventListener {
@EventListener
public void handleUserCreated(UserCreatedEvent event) {
log.info("Nouvel utilisateur: {}", event.getUser().getEmail());
emailService.sendWelcomeEmail(event.getUser());
}
@Async
@EventListener
public void handleUserCreatedAsync(UserCreatedEvent event) {
// Traité de manière asynchrone
}
}
@TransactionalEventListener
Écoute les événements liés à la transaction.
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void handleAfterCommit(OrderCreatedEvent event) {
// Exécuté seulement si la transaction a réussi
notificationService.notifyNewOrder(event.getOrder());
}
8. Annotations REST Client
@FeignClient (Spring Cloud)
Déclare un client REST déclaratif.
@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);
}
Tableau Récapitulatif Global
Les 50+ annotations les plus utilisées
| # | Annotation | Catégorie | Rôle |
|---|---|---|---|
| 1 | @SpringBootApplication | Boot | Point d'entrée |
| 2 | @Component | Core | Bean générique |
| 3 | @Service | Core | Logique métier |
| 4 | @Repository | Core | Accès BDD |
| 5 | @Controller | Web | Contrôleur MVC |
| 6 | @RestController | Web | Contrôleur REST |
| 7 | @Configuration | Core | Classe de config |
| 8 | @Bean | Core | Déclaration de bean |
| 9 | @Autowired | Core | Injection |
| 10 | @Qualifier | Core | Choix du bean |
| 11 | @Value | Core | Injection de valeur |
| 12 | @Profile | Core | Activation par profil |
| 13 | @Scope | Core | Portée du bean |
| 14 | @Lazy | Core | Initialisation différée |
| 15 | @PostConstruct | Core | Init après injection |
| 16 | @PreDestroy | Core | Cleanup avant destruction |
| 17 | @RequestMapping | Web | Mapping URL |
| 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 | Paramètre URL |
| 24 | @RequestParam | Web | Paramètre query |
| 25 | @RequestBody | Web | Corps JSON |
| 26 | @RequestHeader | Web | En-tête HTTP |
| 27 | @ResponseStatus | Web | Code HTTP réponse |
| 28 | @ExceptionHandler | Web | Gestion d'exception |
| 29 | @RestControllerAdvice | Web | Gestion globale erreurs |
| 30 | @CrossOrigin | Web | CORS |
| 31 | @Valid | Validation | Active la validation |
| 32 | @NotNull | Validation | Pas null |
| 33 | @NotBlank | Validation | Pas vide |
| 34 | @Size | Validation | Taille min/max |
| 35 | @Email | Validation | Format email |
| 36 | @Entity | JPA | Entité = table |
| 37 | @Table | JPA | Config table |
| 38 | @Id | JPA | Clé primaire |
| 39 | @GeneratedValue | JPA | Auto-génération ID |
| 40 | @Column | JPA | Config colonne |
| 41 | @OneToMany | JPA | Relation 1:N |
| 42 | @ManyToOne | JPA | Relation N:1 |
| 43 | @ManyToMany | JPA | Relation N:N |
| 44 | @Query | JPA | Requête custom |
| 45 | @Transactional | JPA | Transaction |
| 46 | @EnableWebSecurity | Security | Config sécurité |
| 47 | @PreAuthorize | Security | Autorisation pré-exécution |
| 48 | @SpringBootTest | Test | Test d'intégration |
| 49 | @WebMvcTest | Test | Test contrôleur |
| 50 | @DataJpaTest | Test | Test repository |
| 51 | @MockBean | Test | Mock de bean |
| 52 | @Async | Avancé | Exécution asynchrone |
| 53 | @Scheduled | Avancé | Tâche planifiée |
| 54 | @Cacheable | Avancé | Mise en cache |
| 55 | @EventListener | Avancé | Écoute d'événements |