Can @ManagedPropery and @PostConstruct be placed in a base class?

南楼画角 提交于 2019-12-04 08:49:58

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.

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();
        // ...
    }

}

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() {
        // ...
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!