ripper234
ripper234

Reputation: 230156

Do multiple @Before methods work in Controller inheritance?

I'm trying something similar to this, and only one of the @Before methods gets called:

public abstract class ControllerBase extends Controller {
  @Before
  static void foo() {
    // this actually gets called
  }
}

public class ConcreteController extends ControllerBase {
  @Before
  static void bar() {
    // This DOES NOT get called
  }

  public static void index() {
    render();
  }
}

Is this a bug, feature, or something I'm doing wrong?

Upvotes: 3

Views: 631

Answers (2)

ripper234
ripper234

Reputation: 230156

Yes, Play! will call all the methods in the inheritance hiererchy annotated with @Before.

The problem I ran into was that the @Before I was using was actually org.junit.Before instead of play.mvc.Before !

Upvotes: 0

awm
awm

Reputation: 2768

You're trying to do something weird. And I think your example doesn't match your question. Did you mean to implement ConcreteController on ControllerBase? Rather than both of them extending on Controller?

The @before tag is a concrete class tag. Only the one in the concrete class will get executed.

You can @override the original function, but I don't think that's what you were looking for.

The best way to get what you want is to remove @before from the abstract and from the concrete function call the implemented function you want to run.

public abstract class ControllerBase extends Controller {
  static void foo() {
    // this actually gets called
  }
}

public static class ConcreteController extends Controller {
  @Before
  static void bar() {
    foo();
    // This DOES NOT get called
  }

  public static void index() {
    render();
  }
}

Upvotes: 2

Related Questions