How can you implement method-level security in a Spring application, and what are the advantages of this approach?

Method-level security applies access rules directly to individual methods using annotations, giving finer control than URL security by protecting the actual operation regardless of which entry point triggers it.

Key Points: • @PreAuthorize checks a SpEL condition before the method runs, blocking execution if it fails. • @Secured offers a simpler, role-name-only alternative for straightforward cases. • Requires enabling annotation processing via @EnableMethodSecurity (or the older @EnableGlobalMethodSecurity). • Protects business logic consistently even if it's called from multiple controllers, scheduled jobs, or internal services. • Enables fine-grained rules using method parameters, not just static roles—e.g., checking resource ownership.

Example: A transferFunds() method is annotated with @PreAuthorize("hasRole('ACCOUNT_OWNER')") so the check applies whether it's called from a REST controller or an internal batch job, unlike a URL-only rule which would only cover the HTTP entry point.

Code Example:

@PreAuthorize("hasRole('ACCOUNT_OWNER')")
public void transferFunds(Long accountId, BigDecimal amount) {
    // transfer logic
}

Interview Tip: A concise interview answer is:

"I'd use @PreAuthorize or @Secured on individual methods after enabling @EnableMethodSecurity. The advantage is fine-grained, consistent enforcement at the actual operation, so the rule applies no matter which code path calls the method, not just requests that go through a specific controller endpoint."