@EnableGlobalMethodSecruity注解的作用和示例

@EnableGlobalMethodSecurity 注解用于启用 Spring Security 的方法级别安全性,它提供了许多配置选项,可根据需求进行使用。

下面是一个简单的例子,演示如何在 Spring Boot 应用中使用 @EnableGlobalMethodSecurity 注解:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends GlobalMethodSecurityConfiguration {
}

这里使用了 @EnableGlobalMethodSecurity 注解,通过 prePostEnabled 参数开启了 Spring Security 的方法级别安全性。在 SecurityConfig 类中继承了 GlobalMethodSecurityConfiguration 类,并覆盖了其 configure 方法来自定义一些安全性配置。

当 @EnableGlobalMethodSecurity 注解开启方法级别安全性之后,我们就可以在需要进行安全控制的方法上使用 @PreAuthorize、@PostAuthorize、@Secured 等注解来进行权限控制了。例如:

@Service
public class ProductService {

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public void deleteProduct(String productId) {
        // ...
    }

    @Secured("ROLE_USER")
    public Product getProduct(String productId) {
        // ...
    }
}

在上面的例子中,deleteProduct 方法只能被拥有 ROLE_ADMIN 角色的用户调用,getProduct 方法只能被拥有 ROLE_USER 角色的用户调用。