当我们使用 Play Framework 时 Action Composition我们可以直接使用@With
注解,如explained here 。或者,我们可以定义 custom action annotations .
但是定义自己的注释有什么优点呢?就像我们只是添加一个中间人(接口(interface))。
还有一个疑问:在实现操作类时,我们使用泛型来指定相应的接口(interface)。仅仅是因为 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
类需要注释类型,因为您可以在调用组合操作时检索配置
:
public CompletionStage<Result> call(Context ctx) {
Cached cacheConfiguration = this.configuration;
String key = cacheConfiguration.key();
Long expires = cacheConfiguration.expires();
string region = cacheConfiguration.region();
...
}
最后,定义注释是很好的,因为您可以更好地表达它们的语义(这是一个 @Cached
操作、@Authenticated
操作等)。
关于java - 如果我们可以使用@With注解直接进行 Action 组合,那么为什么我们需要使用接口(interface)创建自定义注解呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42338814/