@PostConstruct of abstract ancestors are not invoked

后端 未结 2 1249
温柔的废话
温柔的废话 2021-01-13 12:53

I\'m writing a JAX-RS library (not an application).

I have:

abstract class A {

    @PostConstruct
    priva         


        
相关标签:
2条回答
  • 2021-01-13 12:59

    According to section Invocation Order of Interceptors Declared on the Target Class of the JSR 318 - Interceptors 1.2 specification:

    Interceptor methods declared on the target class or its superclasses are invoked in the following order:

    • If a target class has superclasses, any interceptor methods defined on those superclasses are invoked, most general superclass first.
    • The interceptor method, if any, on the target class itself is invoked.

    If an interceptor method is overridden by another method (regardless of whether that method is itself an interceptor method), it will not be invoked.

    That means that when writing a library / framework, it is possible to achieve extensibility while using the @PostConstruct lifecyle callback both in the parent class and the child class.

    That mechanism is used in the Camel CDI extension that declares a default Camel context with a @PostConstruct lifecycle callback in https://github.com/astefanutti/camel-cdi/blob/b6f52d91b247e36eefb6f3ecde61016d681d3535/impl/src/main/java/org/apache/camel/cdi/CdiCamelContext.java#L37

    And that can be extended by users like in https://github.com/astefanutti/camel-cdi/blob/b6f52d91b247e36eefb6f3ecde61016d681d3535/envs/se/src/main/java/org/apache/camel/cdi/se/bean/CustomLifecycleCamelContext.java#L37 that declares its own @PostConstruct lifecycle callback.

    Both being called by the container following the specified order.

    That means that your approach is correct from the design standpoint. However, as Jersey dependency injection is based on HK2 and not CDI and relies on bridges like jersey-gf-cdi there might be an issue at that level.

    0 讨论(0)
  • 2021-01-13 13:13

    Annotations are not inherited. You must create a @PostConstruct annotated method for each sub-class.

    To assist/remind the developer, you could require a postConstruct() method and hope the developer annotates it appropriately as suggested by its name:

    public abstract class A {
    
        @PostConstruct // annotation here has no value except as a reminder
        public abstract void postConstruct();  
    
    0 讨论(0)
提交回复
热议问题