繁体   English   中英

如果我们可以使用@With注释直接进行动作组合,那么为什么需要使用接口创建自定义注释?

[英]If we can directly do action composition using @With annotation then why do we need to create custom annotations using interfaces?

当我们使用Play Framework Action Composition时,我们可以直接使用@With注释,如此处所述 或者,我们可以定义自定义动作注释

但是定义自己的注释有什么好处? 就像我们只是添加一个中间人(界面)一样。

还有一个疑问:在实现动作类时,我们使用泛型来指定相应的接口。 仅仅是因为Play是类型安全的吗? 他们在文档中提到了“动作定义将注释作为配置进行检索”。 仅仅是因为我们可以使用自定义注释进行配置吗?

考虑以下注释:

@With(CacheAction.class)
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Cached {
    String key();
    Long expires();
    String region();
}

使用上面的注释,您可以注释操作,例如:

@Cached(
    key = "my.cached.page",
    expires = 30,
    region = "pages"
)
public Result index() {
    ...
}

那么,如何使用@With注释将这些缓存配置传递给组合操作? 你不能。 如果不必配置撰写动作的行为(例如登录文档示例),则@With很好。 但是,如果需要,他们需要声明自己的注释。

Action类需要注释类型,因为您随后configuration在调用组合操作时检索configuration

public CompletionStage<Result> call(Context ctx) {
    Cached cacheConfiguration = this.configuration;
    String key = cacheConfiguration.key();
    Long expires = cacheConfiguration.expires();
    string region = cacheConfiguration.region();

    ...
}

最后,定义自己的注释是好的,因为您可以更好地表达与它们相关的语义(这是@Cached动作,这是@Authenticated动作,等等)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM