Capítulo 4: Anotações Security, Teste e Avançado
1. Anotações Spring Security
@EnableWebSecurity
Ativa a configuração de segurança 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
Ativa a segurança no nível de métodos.
@Configuration
@EnableMethodSecurity // Ativa @PreAuthorize, @PostAuthorize, @Secured
public class MethodSecurityConfig {
}
@PreAuthorize
Verifica as autorizações antes da execução do 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 as autorizações após a execução.
@GetMapping("/{id}")
@PostAuthorize("returnObject.owner == authentication.name or hasRole('ADMIN')")
public Document getDocument(@PathVariable Long id) {
return documentService.findById(id);
}
@Secured
Especifica os papéis necessários (mais simples que @PreAuthorize).
@Secured("ROLE_ADMIN")
public void adminOnly() { ... }
@Secured({"ROLE_ADMIN", "ROLE_MANAGER"})
public void adminOrManager() { ... }
@RolesAllowed
Padrão JSR-250, semelhante ao @Secured.
@RolesAllowed("ADMIN")
public void adminOnly() { ... }
Resumo Security
| Anotação | Uso |
|---|---|
@EnableWebSecurity | Ativa a config Security |
@EnableMethodSecurity | Ativa a segurança por método |
@PreAuthorize | Verificação ANTES da execução (SpEL) |
@PostAuthorize | Verificação APÓS a execução |
@Secured | Papéis necessários (simples) |
@RolesAllowed | Papéis necessários (JSR-250) |
2. Anotações de Teste
@SpringBootTest
Carrega o contexto completo do Spring para testes de integração.
@SpringBootTest
class UserServiceIntegrationTest {
@Autowired
private UserService userService;
@Test
void shouldCreateUser() {
User user = userService.create(new UserDto("Jean", "jean@test.com"));
assertThat(user.getId()).isNotNull();
}
}
// Com um servidor web aleatório
@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
Testa apenas a camada de controlador (sem banco de dados, sem serviços reais).
@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
Testa apenas a camada de persistência 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
Substitui um bean Spring por um mock do Mockito.
@WebMvcTest(UserController.class)
class UserControllerTest {
@MockBean
private UserService userService; // Mock em vez do serviço real
@Test
void shouldReturnUser() {
when(userService.findById(1L)).thenReturn(new User("Jean"));
// ...
}
}
@SpyBean
Envolve um bean real com um spy do Mockito (chamadas reais exceto as stubadas).
@SpringBootTest
class NotificationTest {
@SpyBean
private EmailService emailService;
@Test
void shouldSendEmail() {
doNothing().when(emailService).sendEmail(anyString(), anyString());
// O restante dos métodos chama o código real
}
}
@TestConfiguration
Fornece uma configuração específica para testes.
@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
Ativa um perfil Spring específico para o teste.
@SpringBootTest
@ActiveProfiles("test")
class ServiceTest {
// Usa application-test.yml
}
@Sql / @SqlGroup
Executa scripts SQL antes/depois de um teste.
@DataJpaTest
@Sql("/test-data.sql")
class ProductRepositoryTest {
// test-data.sql é executado antes de cada teste
}
@Sql(scripts = "/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
Resumo Teste
| Anotação | Escopo | Uso |
|---|---|---|
@SpringBootTest | Contexto completo | Testes de integração |
@WebMvcTest | Apenas camada Web | Testes de controladores |
@DataJpaTest | Apenas camada JPA | Testes de repositórios |
@MockBean | Bean mockado | Substituir um bean |
@SpyBean | Bean espionado | Envelopar um bean real |
@ActiveProfiles | Perfil | Escolher a config de teste |
@Sql | Banco de dados | Carregar dados SQL |
3. Anotações Assíncronas e de Agendamento
@EnableAsync / @Async
Executa um método de forma assíncrona (em uma thread separada).
@Configuration
@EnableAsync
public class AsyncConfig {
}
@Service
public class EmailService {
@Async
public CompletableFuture<String> sendEmailAsync(String to, String body) {
// Executado em uma thread separada
// ... envio de email
return CompletableFuture.completedFuture("Email enviado para " + to);
}
}
@EnableScheduling / @Scheduled
Agenda a execução periódica de um método.
@Configuration
@EnableScheduling
public class SchedulingConfig {
}
@Service
public class CleanupService {
@Scheduled(fixedRate = 60000) // A cada 60 segundos
public void cleanupExpiredTokens() {
tokenRepository.deleteExpired();
}
@Scheduled(fixedDelay = 30000) // 30 segundos após o fim da execução anterior
public void processQueue() {
queueService.processNext();
}
@Scheduled(cron = "0 0 2 * * ?") // Todos os dias às 2h da manhã
public void dailyReport() {
reportService.generateDailyReport();
}
@Scheduled(cron = "0 0 * * * MON-FRI") // A cada hora, de segunda a sexta
public void hourlySync() {
syncService.sync();
}
}
Sintaxe Cron
┌───────── segundo (0-59)
│ ┌─────── minuto (0-59)
│ │ ┌───── hora (0-23)
│ │ │ ┌─── dia do mês (1-31)
│ │ │ │ ┌─ mês (1-12)
│ │ │ │ │ ┌ dia da semana (0-7, MON-SUN)
│ │ │ │ │ │
* * * * * *
| Expressão | Descrição |
|---|---|
0 0 * * * * | A cada hora |
0 0 2 * * * | Todos os dias às 2h |
0 0 9-17 * * MON-FRI | A cada hora das 9h às 17h em dias úteis |
0 */15 * * * * | A cada 15 minutos |
0 0 0 1 * * | No primeiro dia de cada mês à meia-noite |
4. Anotações 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 armazenado em cache; chamadas seguintes não acessam o banco
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) {
// Atualiza o cache com o novo resultado
return productRepository.save(product);
}
@CacheEvict(value = "products", key = "#id")
public void delete(Long id) {
// Remove a entrada do cache
productRepository.deleteById(id);
}
@CacheEvict(value = "products", allEntries = true)
public void clearCache() {
// Limpa todo o cache "products"
}
}
5. Anotações AOP (Programação Orientada a Aspectos)
@Aspect / @Before / @After / @Around
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
log.info("Chamada: {}", joinPoint.getSignature().getName());
}
@After("execution(* com.example.service.*.*(..))")
public void logAfter(JoinPoint joinPoint) {
log.info("Fim: {}", 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("{} executado em {} ms", joinPoint.getSignature().getName(), duration);
return result;
}
}
6. Anotações de Auto-Configuração do Spring Boot
@EnableAutoConfiguration
Incluída em @SpringBootApplication. Ativa a configuração automática baseada nas dependências.
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
// Desativa a auto-configuração do DataSource
@ConditionalOn...
Família de anotações para configuração condicional.
| Anotação | Condição |
|---|---|
@ConditionalOnProperty | Propriedade tem um determinado valor |
@ConditionalOnClass | Classe presente no classpath |
@ConditionalOnMissingClass | Classe ausente no classpath |
@ConditionalOnBean | Bean existe no contexto |
@ConditionalOnMissingBean | Bean não existe no contexto |
@ConditionalOnExpression | Expressão SpEL é verdadeira |
@ConditionalOnWebApplication | O app é uma aplicação web |
@ConditionalOnNotWebApplication | O app não é uma aplicação web |
7. Anotações de Messaging e Eventos
@EventListener
Escuta eventos do Spring.
@Component
public class UserEventListener {
@EventListener
public void handleUserCreated(UserCreatedEvent event) {
log.info("Novo usuário: {}", event.getUser().getEmail());
emailService.sendWelcomeEmail(event.getUser());
}
@Async
@EventListener
public void handleUserCreatedAsync(UserCreatedEvent event) {
// Processado de forma assíncrona
}
}
@TransactionalEventListener
Escuta eventos relacionados à transação.
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void handleAfterCommit(OrderCreatedEvent event) {
// Executado apenas se a transação for bem-sucedida
notificationService.notifyNewOrder(event.getOrder());
}
8. Anotações REST Client
@FeignClient (Spring Cloud)
Declara um 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);
}
Tabela Resumo Global
As 50+ anotações mais utilizadas
| # | Anotação | Categoria | Papel |
|---|---|---|---|
| 1 | @SpringBootApplication | Boot | Ponto de entrada |
| 2 | @Component | Core | Bean genérico |
| 3 | @Service | Core | Lógica de negócio |
| 4 | @Repository | Core | Acesso a banco de dados |
| 5 | @Controller | Web | Controller MVC |
| 6 | @RestController | Web | Controller REST |
| 7 | @Configuration | Core | Classe de configuração |
| 8 | @Bean | Core | Declaração de bean |
| 9 | @Autowired | Core | Injeção |
| 10 | @Qualifier | Core | Escolha do bean |
| 11 | @Value | Core | Injeção de valor |
| 12 | @Profile | Core | Ativação por perfil |
| 13 | @Scope | Core | Escopo do bean |
| 14 | @Lazy | Core | Inicialização tardia |
| 15 | @PostConstruct | Core | Init após injeção |
| 16 | @PreDestroy | Core | Cleanup antes da destruição |
| 17 | @RequestMapping | Web | Mapeamento de 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 de URL |
| 24 | @RequestParam | Web | Parâmetro de query |
| 25 | @RequestBody | Web | Corpo JSON |
| 26 | @RequestHeader | Web | Header HTTP |
| 27 | @ResponseStatus | Web | Código HTTP da resposta |
| 28 | @ExceptionHandler | Web | Tratamento de exceção |
| 29 | @RestControllerAdvice | Web | Tratamento global de erros |
| 30 | @CrossOrigin | Web | CORS |
| 31 | @Valid | Validação | Ativa a validação |
| 32 | @NotNull | Validação | Não nulo |
| 33 | @NotBlank | Validação | Não vazio |
| 34 | @Size | Validação | Tamanho min/máx |
| 35 | @Email | Validação | Formato de email |
| 36 | @Entity | JPA | Entidade = tabela |
| 37 | @Table | JPA | Configuração da tabela |
| 38 | @Id | JPA | Chave primária |
| 39 | @GeneratedValue | JPA | Geração automática de ID |
| 40 | @Column | JPA | Configuração da coluna |
| 41 | @OneToMany | JPA | Relação 1:N |
| 42 | @ManyToOne | JPA | Relação N:1 |
| 43 | @ManyToMany | JPA | Relação N:N |
| 44 | @Query | JPA | Consulta customizada |
| 45 | @Transactional | JPA | Transação |
| 46 | @EnableWebSecurity | Security | Configuração de segurança |
| 47 | @PreAuthorize | Security | Autorização pré-execução |
| 48 | @SpringBootTest | Teste | Teste de integração |
| 49 | @WebMvcTest | Teste | Teste de controller |
| 50 | @DataJpaTest | Teste | Teste de repositório |
| 51 | @MockBean | Teste | Mock de bean |
| 52 | @Async | Avançado | Execução assíncrona |
| 53 | @Scheduled | Avançado | Tarefa agendada |
| 54 | @Cacheable | Avançado | Cache de resultado |
| 55 | @EventListener | Avançado | Escuta de eventos |