java - 我必须在接口(interface)或类上放置@Secured 注释吗?

标签 java spring spring-security

@Secured 注释放在接口(interface)方法或实现接口(interface)的类中的方法上是否正确?对此有什么建议吗?

当我深入研究定义 @Secured 注释的类时,我可以看到它具有 @Inherited 注释集:

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Secured {
    /**
     * Returns the list of security configuration attributes (e.g. ROLE_USER, ROLE_ADMIN).
     *
     * @return String[] The secure method attributes
     */
    public String[]value();
}

已阅读this answer ,我想我可以在接口(interface)上设置 @Secured 注释,以一致地对接口(interface)的所有实现实现授权。

最佳答案

在您提供的链接中,@Transactional 也是 @Inherited。让我们分解它们的每个部分。

根据 Spring 的 developers recommended在具体类中使用 @Transactional 注释。 您可以在接口(interface)或接口(interface)内的方法中使用 @Transactional 注释。如果您使用 interface-based-proxies,您可以认为这会如您所愿地工作。未继承的注解是指,如果您正在使用 class-based-proxies,则可能事务属性未应用于该接口(interface)。因此最终对象不能被事务属性覆盖或包裹。

如果是这样,@Secured 注释是@Inherited 那么这可以在接口(interface)及其实现类中使用。 来自 Spring docs :

The Secured annotation is used to define a list of security configuration attributes for business methods.

例如:

 @Secured({ "ROLE_USER" })
 public void create(Contact contact);

 @Secured({ "ROLE_USER", "ROLE_ADMIN" })
 public void update(Contact contact);

 @Secured({ "ROLE_ADMIN" })
 public void delete(Contact contact);

所以归根结底,您可能对一个接口(interface)有多个实现。因此,在界面中保留您的 @Secured 注释是有意义的。

关于java - 我必须在接口(interface)或类上放置@Secured 注释吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47010714/

相关文章:

java - @AfterReturning 拦截aspectJ调用的方法失败

java - 如何在@RequestParam中传递符号&?

java - Spring Boot 2.0.3版中的分页功能不起作用

java - Jboss 6.4 上的 Log4j 2 自定义级别

java - 有人可以帮我(新手)解释抽象类和接口(interface)吗?

java - Spring - 配置 apache commons 电子邮件

linux - Spring Kerberos 扩展、SSO 和域外机器

authentication - Grails 3和Spring Security:用户未登录时返回401

java - 正则表达式检索任何字母数字 otp 代码

java - java中的事件处理程序...程序没​​有错误,但在事件操作未显示后