【问题标题】:@With annotation in Play JavaPlay Java 中的 @With 注释
【发布时间】:2017-06-13 22:18:36
【问题描述】:

我不明白Play Java中@With注解的含义。 我们在 StackOverflow 中有 the same question,它似乎是 Play1,而不是 Play2。 在Play的最新版本文档中,我看到了这个例子。

@With(VerboseAction.class)
public Result verboseIndex() {
    return ok("It works!"); }

这是什么意思?上述情况下,有注解和无注解有什么区别?

【问题讨论】:

    标签: java playframework annotations playframework-2.5


    【解决方案1】:

    很明显@With 用于组合动作:

    public class VerboseAction extends play.mvc.Action.Simple {
        public CompletionStage<Result> call(Http.Context ctx) {
            Logger.info("Calling action for {}", ctx);
            return delegate.call(ctx);
        }
    }
    

    您可以使用 @With 注释将 action 方法提供的代码与另一个 play.mvc.Action 组合起来:

    @With(VerboseAction.class)
    public Result verboseIndex() {
        return ok("It works!");
    }
    

    所以,当verboseIndex 被调用时,首先会调用VerboseActioncall 方法。所以,在这个例子中,首先Logger.info会写一些信息消息,然后ok会完成响应。

    【讨论】:

    • 我明白了。但是,verboseIndex 是一个方法,而VerboseAction 是一个类。所以,对我来说,这很奇怪。你怎么解释?
    • 是的,因为 Action 是 action 方法调用的装饰器。
    • 感谢您的回复。 “装饰器”是什么意思?你解释了当方法verboseIndex被调用时,VerboseAction也被调用了。但在最详细的层面上,我假设应该调用一个方法。那么,当verboseIndex 被调用时,实际上调用了什么? VerboseAction内的方法call?
    • @KazuyaTomita,是的
    • delegate.call方法的返回值是CompletionStage&lt;Result&gt;,可以是Result,所以比如执行verboseIndex方法后,某个Action类中的call方法就会被执行。我说的对吗?
    猜你喜欢
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多