calling @PostConstruct on super bean AND extending bean

◇◆丶佛笑我妖孽 提交于 2019-12-05 03:44:15

The @PostConstruct of the superclass of a backing bean is not called at all when the managed bean is constructed. It's only called when a completely separate managed bean instance of that superclass is been constructed by e.g. using #{baseBean} in EL in your case. You effectively end up with two entirely separate instances #{baseBean} and #{smartBoxSearchBean} wherein the class' own @PostConstruct method is invoked independently on the managed bean class itself.

This design is somewhat strange. A superclass of a backing bean is normally not to be used as a managed bean at all.

I suggest to revise your approach as follows:

public abstract class BaseBean {

    @ManagedProperty("#{contextBean}")
    private ContextBean contextBean;

    public Context getContext() {
        return contextBean.getContext();
    }

}

and

@ManagedBean
@RequestScoped
public class SmartBoxSearchBean extends BaseBean {

    @PostConstruct
    public void setUp() {
        jsonHelper = getContext().get(SmartBoxJsonHelper.class);
    }

}

Or maybe this, if you don't need ContextBean for other purposes at all

public abstract class BaseBean {

    @ManagedProperty("#{contextBean.context}")
    private Context context;

    public Context getContext() {
        return context;
    }

}

Note that @ManagedProperty works just fine when declared in a superclass this way.


Update: depending on the functional requirements, you can also decouple the beans and just inject the #{baseBean} in the {smartBoxSearchBean}.

@ManagedBean
@RequestScoped
public class BaseBean {

    @ManagedProperty("#{contextBean}")
    private ContextBean contextBean;
    private Context context;

    @PostConstruct
    public void init() {
        context = contextBean.getContext();
    }

}

and

@ManagedBean
@RequestScoped
public class SmartBoxSearchBean {

    @ManagedProperty("#{baseBean}")
    private BaseBean baseBean; 

    @PostConstruct
    public void setUp() {
        jsonHelper = baseBean.getContext().get(SmartBoxJsonHelper.class);
    }

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