rivasket
rivasket

Reputation: 377

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

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
}

Upvotes: 4

Views: 4751

Answers (1)

BalusC
BalusC

Reputation: 1108722

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

Upvotes: 6

Related Questions