Get access to session scoped CDI bean from request scoped CDI Bean

坚强是说给别人听的谎言 提交于 2019-12-10 09:26:39

问题


I have already one session scoped CDI bean, which keeps currently logged in user data. Now, from another, request scoped I would like to access to this bean to get some data. I have some operation to do, which is dependent on user login. That's the only information I need.

How to access it?

AccountBean.java:

@Named("accountBean")
@SessionScoped
public class AccountBean implements Serializable {
    private static final long serialVersionUID = 16472027766900196L;

    @Inject
    AccountService accountService;

    private String login;
    private String password;
    // getters and setters ommited
}

Part of login.xhtml:

<h:form>
    <h:panelGrid columns="2">
        #{msgs.loginPrompt}
        <h:inputText id="login" value="#{accountBean.login}" />
        #{msgs.passwordPrompt}
        <h:inputSecret id="password" value="#{accountBean.password}" />
        <h:commandButton value="#{msgs.loginButtonText}"
            action="#{accountBean.login}" />
    </h:panelGrid>
</h:form>

SearchBean.java:

@Named("searchBean")
@RequestScoped
public class SearchBean {
        @Inject AccountBean accountBean;
            // some other stuff
}

回答1:


Just @Inject it.

@Inject
private Bean bean;

Note that this isn't available in the constructor of the receiving bean (it's not possible to inject something in an unconstructed instance, you see). The earliest access point is a @PostConstruct method.

@PostConstruct
public void init() {
    bean.doSomething();
}


来源:https://stackoverflow.com/questions/8512206/get-access-to-session-scoped-cdi-bean-from-request-scoped-cdi-bean

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