Administrator
发布于 2025-10-10 / 7 阅读
0
0

@Secured()、@PreAuthorize()、@RolesAllowed()注解的使用

1. @Secured(): secured_annotation

@Secured({"ROLE_ADMIN"})
public void changePassword(String username, String password);

使用时,需要如下配置Spring Security (无论是通过xml配置,还是在Spring boot下,直接注解配置,都需要指明secured-annotations)
XML: <global-method-security secured-annotations="enabled"/> 
Spring boot: @EnableGlobalMethodSecurity(securedEnabled = true)

2. @RolesAllowed(): jsr250-annotations

@RolesAllowed({"ROLE_ADMIN"})
public void changePassword(String username, String password);

使用时,需要如下配置Spring Security (无论是通过xml配置,还是在Spring boot下,直接注解配置,都需要指明jsr250-annotations)
XML: <global-method-security jsr250-annotations="enabled"/> 
Spring boot:  @EnableGlobalMethodSecurity(jsr250Enabled = true)

3. @PreAuthorize(): pre-post-annotations

@PreAuthorize("hasRole('ROLE_ADMIN')")
public void changePassword(String username, String password);

使用时,需要如下配置Spring Security (无论是通过xml配置,还是在Spring boot下,直接注解配置,都需要指明pre-post-annotations)
XML: <global-method-security pre-post-annotations="enabled"/> 
Spring boot: @EnableGlobalMethodSecurity(prePostEnabled = true)

方法授权类型

声明方式

JSR标准

允许SpEL表达式

@PreAuthorize、@PostAuthorize

注解

No

Yes

@RolesAllowed、@PermitAll、@DenyAll

注解

Yes

No

@Secure

注解

No

No

protect-pointcut

XML

No

No


评论