简体   繁体   中英

What's the difference between @After and @Finally annotations for Play controllers

The documentation isn't very clear on this. Can someone illuminate the differences between these two?

@After - Methods annotated with the @After annotation are executed after each action call for this Controller.

@Finally - Methods annotated with the @Finally annotation are executed after each action result is applied from for this Controller.

Would it hurt performance to use @Finally when @After would work?

If you write a small test harness, you will see how this works, but the crux of it is this

  • @Before is called before you action is executed

  • @After is called after your controller has completed its execution, but before the output is rendered to the browser

  • @Finally is called when the results have been posted to the browser.

So in most cases, @After and @Finally will work for you in the same way, but do have a slight difference, depending on your particular use-case. It shouldn't make any difference to performance however.

The test harness that I wrote to prove this, is as follows

public class Application extends Controller {

    @Before
    static void log0() {Logger.info("before: "+ response.out.size());}
    @After
    static void log1() {Logger.info("After: "+ response.out.size());}
    @Finally
    static void log2() {Logger.info("finally: "+ response.out.size());}

    public static void index() {
        Logger.info("in index action");
        render();
    }
}

The output I get is as follows

20:51:37,741 INFO  ~ before: 0
20:51:37,742 INFO  ~ in index action
20:51:38,083 INFO  ~ After: 0
20:51:38,106 INFO  ~ finally: 706

Which clearly shows the order of processing, and the data being outputted to the the HTTP Response object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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