mathk
mathk

Reputation: 8133

PostContruct annotation on superclass

I want to refactor a method annotated with @PostContruct in a common class of all my controller.

public abstract class Controller {
    @PostConstruct
    protected void PostContruct() { ..}
}

public class AuthController extends Controller {}

public class CartController extends Controller {}

But spring doesn't seems to call my inherit method. What is the pattern to use in this situation ?

Upvotes: 2

Views: 983

Answers (1)

cahen
cahen

Reputation: 16636

This works with Spring 4.2.0 and Spring Boot 1.2.5

public abstract class AbstractController {
    @PostConstruct
    protected void postConstruct() {
        System.out.println("post construct");
    }
}

@Controller
public class ConcreteController extends AbstractController {

}

It also works if you mark the method as abstract, keep the @PostConstruct in the parent and implement it in the child.

It does NOT work if @Controller is in the parent.

Upvotes: 2

Related Questions