Programming/JSF

Life Cycle Annotations

Jared 2008. 7. 7. 16:38

Starting with JSF 1.2, you can specify managed bean methods that are automatically called just after the bean has been constructed and just before the bean goes out of scope. This is particularly convenient for beans that establish connections to external resources such as databases.

Annotate the methods with @PostConstruct or @PreDestroy, like this:

public class MyBean {
    @PostConstruct
    public void initialize() {
        // initialization code
    }
    @PreDestroy
    public void shutdown() {
        // shutdown code
    }

    // other bean methods
}

These methods will be automatically called, provided the web application is deployed in a container that supports the annotations of JSR (Java Specification Request) 250 (see http://www.jcp.org/en/jsr/detail?id=250). Inparticular, Java EE 5 compliant application servers such as GlassFish support these annotations. It is expected that standalone containers such as Tomcat will also provide support in the future.