Saltar al contenido principal

Capítulo 4: Anotaciones Security, Test y Avanzadas

1. Anotaciones Spring Security​

@EnableWebSecurity​

Activa la configuración de seguridad personalizada.

@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​

Activa la seguridad a nivel de métodos.

@Configuration
@EnableMethodSecurity // Activa @PreAuthorize, @PostAuthorize, @Secured
public class MethodSecurityConfig {
}

@PreAuthorize​

Verifica los permisos antes de la ejecución del método.

@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​

Verifica los permisos después de la ejecución.

@GetMapping("/{id}")
@PostAuthorize("returnObject.owner == authentication.name or hasRole('ADMIN')")
public Document getDocument(@PathVariable Long id) {
return documentService.findById(id);
}

@Secured​

Especifica los roles requeridos (más simple que @PreAuthorize).

@Secured("ROLE_ADMIN")
public void adminOnly() { ... }

@Secured({"ROLE_ADMIN", "ROLE_MANAGER"})
public void adminOrManager() { ... }

@RolesAllowed​

Estándar JSR-250, similar a @Secured.

@RolesAllowed("ADMIN")
public void adminOnly() { ... }

Resumen Security​

AnotaciónUso
@EnableWebSecurityActiva la config Security
@EnableMethodSecurityActiva la seguridad por método
@PreAuthorizeVerificación ANTES de ejecución (SpEL)
@PostAuthorizeVerificación DESPUÉS de ejecución
@SecuredRoles requeridos (simple)
@RolesAllowedRoles requeridos (JSR-250)

2. Anotaciones de Test​

@SpringBootTest​

Carga el contexto completo de Spring para pruebas de integración.

@SpringBootTest
class UserServiceIntegrationTest {

@Autowired
private UserService userService;

@Test
void shouldCreateUser() {
User user = userService.create(new UserDto("Jean", "jean@test.com"));
assertThat(user.getId()).isNotNull();
}
}

// Con un servidor web aleatorio
@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​

Prueba solo la capa de controlador (sin BDD, sin servicios reales).

@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​

Prueba solo la capa de persistencia 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​

Reemplaza un bean de Spring por un mock de Mockito.

@WebMvcTest(UserController.class)
class UserControllerTest {

@MockBean
private UserService userService; // Mock en lugar del servicio real

@Test
void shouldReturnUser() {
when(userService.findById(1L)).thenReturn(new User("Jean"));
// ...
}
}

@SpyBean​

Envuelve un bean real con un spy de Mockito (llamadas reales excepto las stub).

@SpringBootTest
class NotificationTest {

@SpyBean
private EmailService emailService;

@Test
void shouldSendEmail() {
doNothing().when(emailService).sendEmail(anyString(), anyString());
// El resto de los métodos llama al código real
}
}

@TestConfiguration​

Proporciona una configuración específica para pruebas.

@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​

Activa un perfil específico de Spring para la prueba.

@SpringBootTest
@ActiveProfiles("test")
class ServiceTest {
// Usa application-test.yml
}

@Sql / @SqlGroup​

Ejecuta scripts SQL antes/después de una prueba.

@DataJpaTest
@Sql("/test-data.sql")
class ProductRepositoryTest {
// test-data.sql se ejecuta antes de cada prueba
}

@Sql(scripts = "/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)

Resumen Test​

AnotaciónAlcanceUso
@SpringBootTestContexto completoPruebas de integración
@WebMvcTestSolo capa WebPruebas de controladores
@DataJpaTestSolo capa JPAPruebas de repositorios
@MockBeanBean mockeadoReemplazar un bean
@SpyBeanBean espiadoWrapper de un bean real
@ActiveProfilesPerfilElegir la config de test
@SqlBDDCargar datos SQL

3. Anotaciones Asíncronas y de Planificación​

@EnableAsync / @Async​

Ejecuta un método de manera asíncrona (en un hilo separado).

@Configuration
@EnableAsync
public class AsyncConfig {
}

@Service
public class EmailService {

@Async
public CompletableFuture<String> sendEmailAsync(String to, String body) {
// Ejecutado en un hilo separado
// ... envío de email
return CompletableFuture.completedFuture("Email enviado a " + to);
}
}

@EnableScheduling / @Scheduled​

Programa la ejecución periódica de un método.

@Configuration
@EnableScheduling
public class SchedulingConfig {
}

@Service
public class CleanupService {

@Scheduled(fixedRate = 60000) // Cada 60 segundos
public void cleanupExpiredTokens() {
tokenRepository.deleteExpired();
}

@Scheduled(fixedDelay = 30000) // 30 segundos después de la ejecución previa
public void processQueue() {
queueService.processNext();
}

@Scheduled(cron = "0 0 2 * * ?") // Todos los días a las 2 a.m.
public void dailyReport() {
reportService.generateDailyReport();
}

@Scheduled(cron = "0 0 * * * MON-FRI") // Cada hora, de lunes a viernes
public void hourlySync() {
syncService.sync();
}
}

Sintaxis Cron​

┌───────── segundo (0-59)
│ ┌─────── minuto (0-59)
│ │ ┌───── hora (0-23)
│ │ │ ┌─── día del mes (1-31)
│ │ │ │ ┌─ mes (1-12)
│ │ │ │ │ ┌ día de la semana (0-7, MON-SUN)
│ │ │ │ │ │
* * * * * *
ExpresiónDescripción
0 0 * * * *Cada hora
0 0 2 * * *Todos los días a las 2
0 0 9-17 * * MON-FRICada hora de 9 a 17 en días laborables
0 */15 * * * *Cada 15 minutos
0 0 0 1 * *El primero de cada mes a medianoche

4. Anotaciones 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) {
// Resultado cacheado; las siguientes llamadas no acceden a 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) {
// Actualiza el cache con el nuevo resultado
return productRepository.save(product);
}

@CacheEvict(value = "products", key = "#id")
public void delete(Long id) {
// Elimina la entrada del cache
productRepository.deleteById(id);
}

@CacheEvict(value = "products", allEntries = true)
public void clearCache() {
// Vacía todo el cache "products"
}
}

5. Anotaciones AOP (Programación Orientada a Aspectos)​

@Aspect / @Before / @After / @Around​

@Aspect
@Component
public class LoggingAspect {

@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
log.info("Llamada: {}", 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("{} ejecutado en {} ms", joinPoint.getSignature().getName(), duration);
return result;
}
}

6. Anotaciones Spring Boot Auto-Configuration​

@EnableAutoConfiguration​

Incluida en @SpringBootApplication. Activa la configuración automática basada en las dependencias.

@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
// Desactiva la auto-configuración de DataSource

@ConditionalOn...​

Familia de anotaciones para configuración condicional.

AnotaciónCondición
@ConditionalOnPropertyPropiedad tiene cierto valor
@ConditionalOnClassClase presente en el classpath
@ConditionalOnMissingClassClase ausente en el classpath
@ConditionalOnBeanBean existe en el contexto
@ConditionalOnMissingBeanBean no existe en el contexto
@ConditionalOnExpressionExpresión SpEL es verdadera
@ConditionalOnWebApplicationLa app es una app web
@ConditionalOnNotWebApplicationLa app no es una app web

7. Anotaciones de Mensajería y Eventos​

@EventListener​

Escucha los eventos de Spring.

@Component
public class UserEventListener {

@EventListener
public void handleUserCreated(UserCreatedEvent event) {
log.info("Nuevo usuario: {}", event.getUser().getEmail());
emailService.sendWelcomeEmail(event.getUser());
}

@Async
@EventListener
public void handleUserCreatedAsync(UserCreatedEvent event) {
// Procesado de manera asíncrona
}
}

@TransactionalEventListener​

Escucha los eventos relacionados con la transacción.

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void handleAfterCommit(OrderCreatedEvent event) {
// Ejecutado solo si la transacción fue exitosa
notificationService.notifyNewOrder(event.getOrder());
}

8. Anotaciones REST Client​

@FeignClient (Spring Cloud)​

Declara un cliente REST declarativo.

@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);
}

Tabla Resumen Global​

Las 50+ anotaciones más utilizadas​

#AnotaciónCategoríaRol
1@SpringBootApplicationBootPunto de entrada
2@ComponentCoreBean genérico
3@ServiceCoreLógica de negocio
4@RepositoryCoreAcceso BDD
5@ControllerWebControlador MVC
6@RestControllerWebControlador REST
7@ConfigurationCoreClase de configuración
8@BeanCoreDeclaración de bean
9@AutowiredCoreInyección
10@QualifierCoreSelección de bean
11@ValueCoreInyección de valor
12@ProfileCoreActivación por perfil
13@ScopeCoreÁmbito del bean
14@LazyCoreInicialización diferida
15@PostConstructCoreInit después de inyección
16@PreDestroyCoreCleanup antes de destrucción
17@RequestMappingWebMapping URL
18@GetMappingWebHTTP GET
19@PostMappingWebHTTP POST
20@PutMappingWebHTTP PUT
21@DeleteMappingWebHTTP DELETE
22@PatchMappingWebHTTP PATCH
23@PathVariableWebParámetro URL
24@RequestParamWebParámetro query
25@RequestBodyWebCuerpo JSON
26@RequestHeaderWebEncabezado HTTP
27@ResponseStatusWebCódigo HTTP respuesta
28@ExceptionHandlerWebManejo de excepciones
29@RestControllerAdviceWebManejo global de errores
30@CrossOriginWebCORS
31@ValidValidaciónActiva la validación
32@NotNullValidaciónNo nulo
33@NotBlankValidaciónNo vacío
34@SizeValidaciónTamaño min/máx
35@EmailValidaciónFormato email
36@EntityJPAEntidad = tabla
37@TableJPAConfig tabla
38@IdJPAClave primaria
39@GeneratedValueJPAAuto-generación ID
40@ColumnJPAConfig columna
41@OneToManyJPARelación 1:N
42@ManyToOneJPARelación N:1
43@ManyToManyJPARelación N:N
44@QueryJPAConsulta personalizada
45@TransactionalJPATransacción
46@EnableWebSecuritySecurityConfiguración de seguridad
47@PreAuthorizeSecurityAutorización pre-ejecución
48@SpringBootTestTestPrueba de integración
49@WebMvcTestTestPrueba de controlador
50@DataJpaTestTestPrueba de repositorio
51@MockBeanTestMock de bean
52@AsyncAvanzadoEjecución asíncrona
53@ScheduledAvanzadoTarea programada
54@CacheableAvanzadoCacheo
55@EventListenerAvanzadoEscucha de eventos

⬅️ Volver al Módulo 17 | ⬅️ Volver al inicio