0

I'm new to Java EE and I have a task to do but no idea how to do it. I need to create a manged bean that will be scoped on the application. Everytime we start the application, the bean needs to load a list of data from database. So, according to my research on the web, I need:

  1. Create a managed Bean.
  2. Add the bean name to faces-config as an application scoped bean.
  3. On the bean, add all the methods to load the datas.

So how to set loading at the application start-up ? And then how to get these loaded datas from anywhere in the app?

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Hubert Solecki
  • 2,611
  • 5
  • 31
  • 63
  • possible duplicate of [EJB3: Right way to insert initial data when application starts like Grails Bootstrap?](http://stackoverflow.com/questions/24725062/ejb3-right-way-to-insert-initial-data-when-application-starts-like-grails-boots) – perissf Jul 23 '14 at 14:16
  • Are you sure you want to use a managed bean and not say a far more scalable cache solution such as EHCache? http://ehcache.org/ – Gimby Jul 23 '14 at 15:44
  • Same as you, I would not use managed bean but I'm not responsible for the technical solutions unfortunatly... – Hubert Solecki Jul 23 '14 at 15:45
  • 1
    `how to get these loaded datas from anywhere in the app?` That's a design problem. If you use a managed bean for that, you'll make that data only accesible from JSF/Http Session. What you need is to use an EJB or similar as it's mentioned here. – Aritz Jul 28 '14 at 06:13

1 Answers1

3

This is quite easy since JSF 2.x, just add attribute eager to the @ManagedBean annotation.

@ApplicationScoped
@ManagedBean(eager=true)
public class InitializerBean {

    @PostConstruct
    public void init() {
         //init your DB here
    }

}
Petr Mensik
  • 26,874
  • 17
  • 90
  • 115
  • Thank you for the answer. I put the eager property on the definition of the managed bean in faces-config. Then I wanted to see if it works so I put an info logger in the Init method but it shows nothing when I start the app, is it normal ? – Hubert Solecki Jul 23 '14 at 15:41
  • This depends on the settings for your logger. And also what do you mean by "start the app"?This bean will be created on first access of some JSF page, not during application deployment. – Petr Mensik Jul 23 '14 at 15:49
  • That might be a reason, are you using `javax.faces.bean` package? – Petr Mensik Jul 23 '14 at 18:37
  • @HubertSolecki what version of JSF are you using ? –  Jul 23 '14 at 19:33