0 day streak
java / intermediate
Snippet

Method-Level Security with @PreAuthorize

Spring Security's @PreAuthorize allows you to define access control rules directly on methods using SpEL (Spring Expression Language).

snippet.java
java
1
2
3
4
5
6
7
8
@Service
public class AdminService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) {
// Business logic to delete user
}
}
spring
Breakdown
1
@PreAuthorize("hasRole('ADMIN')")
Checks if the currently authenticated user has the 'ADMIN' role before entering the method.