Search code examples
javajavabeanscdijava-ee-7

Java EE 7 containers: initialize bean at startup without adding it to beans.xml?


Is there any bean type or Java EE annotation to get a bean initialized at container startup without adding the bean to beans.xml?


Solution

  • Yes, there is.
    This is what I use when I need a singleton, application scoped bean started on deploy:

    import javax.ejb.Singleton;
    import javax.ejb.Startup;
    import javax.enterprise.context.ApplicationScoped;
    import javax.inject.Named;
    import javax.annotation.PostConstruct;
    
    @Named( "myBean" )
    @ApplicationScoped
    @Startup
    @Singleton
    public class MyBean {
        @PostConstruct
        public void postConstruct() {}
    }
    

    The postConstruct method is added if you need any code to be executed besides initialization.