Search code examples
springjsfcdi

How to Lazy Load the @Named Bean


I have a SessionScoped Named Bean as follows:

@Named("userBean")
@SessionScoped
public class UserBean implements Serializable {
  .....
   @PostConstruct
      public void init()
       {
            ...call some methods to fetch some data
       }

Now the problem is, while deploying the application, init() will be called, and through-out the session it will not be called again. My requirement is to make the init() call only when the bean is required to be initialized. How can this be achieved?


Solution

  • @Named("userBean")
    @SessionScoped
    @Lazy
    public class UserBean implements Serializable
    

    And wherever you have @Autowired UserBean

    make it

    @Lazy
    @Autowired
    UserBean userbean;