【问题标题】:Initialize subclasses after @PostConstruct在@PostConstruct 之后初始化子类
【发布时间】:2015-06-02 15:29:12
【问题描述】:

我在 WildFly 8.2 应用服务器中使用 JavaEE 7 的上下文依赖注入 CDI 1.1 框架

我想在超类的@PostConstruct之后初始化子类

所以我会这样做

// case 1: it's working but it's not simple to understand

public class A {

    @PostConstruct
    protected void init() {
        System.out.println("A");
        afterInit();
    }

    protected void afterInit() {}

}

public class B extends A {

    @Override
    protected void afterInit() {
        System.out.println("B");
    }

}


public class C extends B {

    @Override
    protected void afterInit() {
        super.afterInit();
        System.out.println("C");
    }

}

所以init()方法会按这个顺序打印A、B、C

有一个 @AfterPostconstruct 注释会做同样的事情,但我不知道

// case 2: dream code

public class A {

    @PostConstruct
    protected void init() {
        System.out.println("A");
    }

}

public class B extends A {

    @AfterPostConstruct  // pseudocode
    protected void afterInitB() {
        System.out.println("B");
    }

}


public class C extends B {

    @AfterPostConstruct // pseudocode
    protected void afterInitC() {
        System.out.println("C");
    }

}

我尝试覆盖init(),但它不起作用(容器不调用init()

// case 3 : code that is not working but it would be better than case 1

public class A {

    @PostConstruct
    protected void init() {
        System.out.println("A");
    }

}

public class B extends A {

    @Override
    protected void init() {
        super.init();
        System.out.println("B");
    }

}


public class C extends B {

    @Override
    protected void init() {
        super.init();
        System.out.println("C");
    }

} 

@PostConstruct 之后有没有更好(更简单)的方法来初始化子类?

【问题讨论】:

    标签: jakarta-ee cdi


    【解决方案1】:

    根据JSR 318 - Interceptors 1.2(也适用于 CDI 1.1)规范的在目标类上声明的拦截器的调用顺序部分:

    在目标类或其超类上声明的拦截器方法 按以下顺序调用:

    • 如果目标类具有超类,则会调用在这些超类上定义的任何拦截器方法,首先是最通用的超类。
    • 调用目标类本身的拦截器方法(如果有)。

    如果一个拦截器方法被另一个方法覆盖(不管 是否该方法本身是一个拦截器方法),它不会 被调用。

    所以在你的用例中,你可以这样写:

    public class A {
    
        @PostConstruct
        private void initA() {
            System.out.println("A");
        }
    }
    
    public class B extends A {
    
        @PostConstruct
        private void initB() {
            System.out.println("B");
        }
    }
    
    public class C extends B {
    
        @PostConstruct
        private void initC() {
            System.out.println("C");
        }
    } 
    

    然后按顺序打印:A、B、C。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      • 2014-04-17
      • 2016-04-08
      • 2018-08-23
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      相关资源
      最近更新 更多