可以将@ManagedPropery和@PostConstruct放在基类中吗? [英] Can @ManagedPropery and @PostConstruct be placed in a base class?
问题描述
我正在使用类的层次结构,而我最想尝试做的是让@ManagedBean
继承具有@ManagedProperty
成员和@PostConstruct
方法的类.
I'm using a hierarchy of classes and what I would optimally try to do is have @ManagedBean
's that inherit a class that have @ManagedProperty
members and @PostConstruct
methods.
具体来说,这行得通吗? :
Specifically, will this work? :
public class A {
@ManagedProperty
private C c;
@PostConstruct
public void init() {
// Do some initialization stuff
}
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
}
@ManagedBean
@SessionScoped
public class B extends A {
// Content...
}
预先感谢!
推荐答案
@ManagedProperty
是继承的,将以这种方式工作.如果子类本身没有@PostConstruct
方法,则@PostConstruct
也将被继承.即只能有一个.因此,如果子类本身具有@PostConstruct
,则不会调用超类的"@PostConstruct
".
The @ManagedProperty
is inherited and will just work that way. The @PostConstruct
will also be inherited, provided that the subclass itself doesn't have a @PostConstruct
method. There can namely be only one. So if the subclass itself has a @PostConstruct
, then the superclass' one won't be invoked.
因此,如果您在子类中覆盖@PostConstruct
,则需要显式调用超类的那个.
So if you override the @PostConstruct
in the subclass, then you'd need to explicitly invoke the superclass' one.
public class SuperBean {
@PostConstruct
public void init() {
// ...
}
}
@ManagedBean
public class SubBean extends SuperBean {
@PostConstruct
public void init() {
super.init();
// ...
}
}
或者,提供子类必须实现的抽象方法(没有@PostConstruct
!).
Alternatively, provide an abstract method which the subclass must implement (without @PostConstruct
!).
public class SuperBean {
@PostConstruct
public void superInit() {
// ...
init();
}
public abstract void init();
}
@ManagedBean
public class SubBean extends SuperBean {
@Override
public void init() {
// ...
}
}
这篇关于可以将@ManagedPropery和@PostConstruct放在基类中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!