我在WildFly 8.2应用服务器中使用JavaEE 7中的Context Dependency Injection 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
之后初始化子类?
答案 0 :(得分:5)
根据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。