Useful when the rule depends on the arguments rather than the path.
@EnableMethodSecurity
@Configuration
class SecurityConfig { }
@Service
class OrderService {
@PreAuthorize("hasRole('ADMIN') or #username == authentication.name")
public List<Order> ordersOf(String username) { ... }
@PostAuthorize("returnObject.owner == authentication.name")
public Order byId(Long id) { ... }
}
An admin sees anyone's orders.
A user sees only their own - enforced in one line, next to the method it protects.
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-08-11