gpt4 book ai didi

jakarta-ee - @PostConstruct之后初始化子类

转载 作者:行者123 更新时间:2023-12-04 01:44:44 28 4
gpt4 key购买 nike

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

我想在父类(super class)的 @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之后是否有更好(更简单)的方法来初始化子类?

最佳答案

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

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.

因此,在您的用例中,您可以编写:

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。

关于jakarta-ee - @PostConstruct之后初始化子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30600346/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com