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ón | Uso |
|---|---|
@EnableWebSecurity | Activa la config Security |
@EnableMethodSecurity | Activa la seguridad por método |
@PreAuthorize | Verificación ANTES de ejecución (SpEL) |
@PostAuthorize | Verificación DESPUÉS de ejecución |
@Secured | Roles requeridos (simple) |
@RolesAllowed | Roles 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ón | Alcance | Uso |
|---|---|---|
@SpringBootTest | Contexto completo | Pruebas de integración |
@WebMvcTest | Solo capa Web | Pruebas de controladores |
@DataJpaTest | Solo capa JPA | Pruebas de repositorios |
@MockBean | Bean mockeado | Reemplazar un bean |
@SpyBean | Bean espiado | Wrapper de un bean real |
@ActiveProfiles | Perfil | Elegir la config de test |
@Sql | BDD | Cargar 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ón | Descripción |
|---|---|
0 0 * * * * | Cada hora |
0 0 2 * * * | Todos los días a las 2 |
0 0 9-17 * * MON-FRI | Cada 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ón | Condición |
|---|---|
@ConditionalOnProperty | Propiedad tiene cierto valor |
@ConditionalOnClass | Clase presente en el classpath |
@ConditionalOnMissingClass | Clase ausente en el classpath |
@ConditionalOnBean | Bean existe en el contexto |
@ConditionalOnMissingBean | Bean no existe en el contexto |
@ConditionalOnExpression | Expresión SpEL es verdadera |
@ConditionalOnWebApplication | La app es una app web |
@ConditionalOnNotWebApplication | La 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ón | Categoría | Rol |
|---|---|---|---|
| 1 | @SpringBootApplication | Boot | Punto de entrada |
| 2 | @Component | Core | Bean genérico |
| 3 | @Service | Core | Lógica de negocio |
| 4 | @Repository | Core | Acceso BDD |
| 5 | @Controller | Web | Controlador MVC |
| 6 | @RestController | Web | Controlador REST |
| 7 | @Configuration | Core | Clase de configuración |
| 8 | @Bean | Core | Declaración de bean |
| 9 | @Autowired | Core | Inyección |
| 10 | @Qualifier | Core | Selección de bean |
| 11 | @Value | Core | Inyección de valor |
| 12 | @Profile | Core | Activación por perfil |
| 13 | @Scope | Core | Ámbito del bean |
| 14 | @Lazy | Core | Inicialización diferida |
| 15 | @PostConstruct | Core | Init después de inyección |
| 16 | @PreDestroy | Core | Cleanup antes de destrucción |
| 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 | Parámetro URL |
| 24 | @RequestParam | Web | Parámetro query |
| 25 | @RequestBody | Web | Cuerpo JSON |
| 26 | @RequestHeader | Web | Encabezado HTTP |
| 27 | @ResponseStatus | Web | Código HTTP respuesta |
| 28 | @ExceptionHandler | Web | Manejo de excepciones |
| 29 | @RestControllerAdvice | Web | Manejo global de errores |
| 30 | @CrossOrigin | Web | CORS |
| 31 | @Valid | Validación | Activa la validación |
| 32 | @NotNull | Validación | No nulo |
| 33 | @NotBlank | Validación | No vacío |
| 34 | @Size | Validación | Tamaño min/máx |
| 35 | @Email | Validación | Formato email |
| 36 | @Entity | JPA | Entidad = tabla |
| 37 | @Table | JPA | Config tabla |
| 38 | @Id | JPA | Clave primaria |
| 39 | @GeneratedValue | JPA | Auto-generación ID |
| 40 | @Column | JPA | Config columna |
| 41 | @OneToMany | JPA | Relación 1:N |
| 42 | @ManyToOne | JPA | Relación N:1 |
| 43 | @ManyToMany | JPA | Relación N:N |
| 44 | @Query | JPA | Consulta personalizada |
| 45 | @Transactional | JPA | Transacción |
| 46 | @EnableWebSecurity | Security | Configuración de seguridad |
| 47 | @PreAuthorize | Security | Autorización pre-ejecución |
| 48 | @SpringBootTest | Test | Prueba de integración |
| 49 | @WebMvcTest | Test | Prueba de controlador |
| 50 | @DataJpaTest | Test | Prueba de repositorio |
| 51 | @MockBean | Test | Mock de bean |
| 52 | @Async | Avanzado | Ejecución asíncrona |
| 53 | @Scheduled | Avanzado | Tarea programada |
| 54 | @Cacheable | Avanzado | Cacheo |
| 55 | @EventListener | Avanzado | Escucha de eventos |