Note that there are some explanatory texts on larger screens.

plurals
  1. POPostConstruct in CDI SessionScoped managed beans
    primarykey
    data
    text
    <p>Short story: I have a CDI <code>@SessionScoped</code> bean (annotation from <code>javax.enterprise.context</code> and not from <code>javax.faces</code>) called <code>UserContextBean</code>. I'd like to actually do something when an HTTP session is created. </p> <p>So naturally I assumed that <code>@PostConstruct</code> would do the trick: get called only once when an instance of this bean is constructed. However, as per the documentation <a href="http://docs.oracle.com/javaee/6/tutorial/doc/gmgkd.html" rel="nofollow">here</a>, they say that the PostConstruct method is called :</p> <blockquote> <p>When the managed bean is injected into a component, CDI calls the method after all injection has occurred and after all initializers have been called.</p> </blockquote> <p>I had assumed that the post construct method would be called once, per session. However, practice is consistent with the documentation. This bean is injected into a <code>@RequestScoped</code> bean (also CDI) which serves as a backing bean for a JSF page and the PostConstruct method is called <strong>for every request</strong>. </p> <p>I realize (now) that this is the behavior. But would there be any other way of doing a one time per session initialization? </p> <p>Some code, although not very relevant:</p> <pre><code>@Named(UserContextBean.BEAN_NAME) @SessionScoped public class UserContextBean implements Serializable { ... @PostConstruct private void createSession() { System.out.println("UserContext created."); } } </code></pre> <p>The request scoped bean where I inject this:</p> <pre><code>public abstract class WebPageDataProvider extends AbstractViewDataProvider { @Inject private UserContextBean userContext; </code></pre> <p>I was also thinking to use an <code>HttpSessionListener</code> and initialize the session bean, but it already sounds messy.</p> <p><strong>EDIT</strong></p> <p>Just noticed now that the HTTP session is not even created. If I create the session "manually", by calling <code>getSession(true)</code> (I do this inside a phase listener, for testing purposes, but only because it was already there) then everything works as expected. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload