Pular para o conteúdo principal

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çãoUso
@EnableWebSecurityAtiva a config Security
@EnableMethodSecurityAtiva a segurança por método
@PreAuthorizeVerificação ANTES da execução (SpEL)
@PostAuthorizeVerificação APÓS a execução
@SecuredPapéis necessários (simples)
@RolesAllowedPapé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çãoEscopoUso
@SpringBootTestContexto completoTestes de integração
@WebMvcTestApenas camada WebTestes de controladores
@DataJpaTestApenas camada JPATestes de repositórios
@MockBeanBean mockadoSubstituir um bean
@SpyBeanBean espionadoEnvelopar um bean real
@ActiveProfilesPerfilEscolher a config de teste
@SqlBanco de dadosCarregar 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ãoDescrição
0 0 * * * *A cada hora
0 0 2 * * *Todos os dias às 2h
0 0 9-17 * * MON-FRIA 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çãoCondição
@ConditionalOnPropertyPropriedade tem um determinado valor
@ConditionalOnClassClasse presente no classpath
@ConditionalOnMissingClassClasse ausente no classpath
@ConditionalOnBeanBean existe no contexto
@ConditionalOnMissingBeanBean não existe no contexto
@ConditionalOnExpressionExpressão SpEL é verdadeira
@ConditionalOnWebApplicationO app é uma aplicação web
@ConditionalOnNotWebApplicationO 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çãoCategoriaPapel
1@SpringBootApplicationBootPonto de entrada
2@ComponentCoreBean genérico
3@ServiceCoreLógica de negócio
4@RepositoryCoreAcesso a banco de dados
5@ControllerWebController MVC
6@RestControllerWebController REST
7@ConfigurationCoreClasse de configuração
8@BeanCoreDeclaração de bean
9@AutowiredCoreInjeção
10@QualifierCoreEscolha do bean
11@ValueCoreInjeção de valor
12@ProfileCoreAtivação por perfil
13@ScopeCoreEscopo do bean
14@LazyCoreInicialização tardia
15@PostConstructCoreInit após injeção
16@PreDestroyCoreCleanup antes da destruição
17@RequestMappingWebMapeamento de URL
18@GetMappingWebHTTP GET
19@PostMappingWebHTTP POST
20@PutMappingWebHTTP PUT
21@DeleteMappingWebHTTP DELETE
22@PatchMappingWebHTTP PATCH
23@PathVariableWebParâmetro de URL
24@RequestParamWebParâmetro de query
25@RequestBodyWebCorpo JSON
26@RequestHeaderWebHeader HTTP
27@ResponseStatusWebCódigo HTTP da resposta
28@ExceptionHandlerWebTratamento de exceção
29@RestControllerAdviceWebTratamento global de erros
30@CrossOriginWebCORS
31@ValidValidaçãoAtiva a validação
32@NotNullValidaçãoNão nulo
33@NotBlankValidaçãoNão vazio
34@SizeValidaçãoTamanho min/máx
35@EmailValidaçãoFormato de email
36@EntityJPAEntidade = tabela
37@TableJPAConfiguração da tabela
38@IdJPAChave primária
39@GeneratedValueJPAGeração automática de ID
40@ColumnJPAConfiguração da coluna
41@OneToManyJPARelação 1:N
42@ManyToOneJPARelação N:1
43@ManyToManyJPARelação N:N
44@QueryJPAConsulta customizada
45@TransactionalJPATransação
46@EnableWebSecuritySecurityConfiguração de segurança
47@PreAuthorizeSecurityAutorização pré-execução
48@SpringBootTestTesteTeste de integração
49@WebMvcTestTesteTeste de controller
50@DataJpaTestTesteTeste de repositório
51@MockBeanTesteMock de bean
52@AsyncAvançadoExecução assíncrona
53@ScheduledAvançadoTarefa agendada
54@CacheableAvançadoCache de resultado
55@EventListenerAvançadoEscuta de eventos

⬅️ Voltar ao Módulo 17 | ⬅️ Voltar para o início