Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 704
Brad Mace Avatar asked Dec 16 '22 20:12

Brad Mace


1 Answers

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.

like image 104
Codemwnci Avatar answered Jan 01 '23 15:01

Codemwnci