【发布时间】: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