12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 8 ■ CALLBACKS AND INTERCEPTORS• The method can have public, private, protected, or package-level access, butmust not be static or final.• A method may be annotated <strong>with</strong> multiple annotations (the init() method shownlater in Listing 8-2 is annotated <strong>with</strong> @PostConstruct and @PostActivate).However, only one annotation of a given type may be present on a bean (you can’thave two @PostConstruct annotations in the same session bean, for example).• A callback method can access the beans’ environment entries (see the“Environment Naming Context” section in Chapter 7).These callbacks are typically used to allocate and/or release the bean’s resources. As an example,Listing 8-1 shows the singleton bean CacheEJB using a @PostConstruct annotation to initialize its cache.Straight after creating the single instance of the CacheEJB, the container invokes the initCache() method.Listing 8-1. A Singleton Initializing Its Cache <strong>with</strong> the @PostConstruct Annotation@Singletonpublic class CacheEJB {private Map cache = new HashMap();@PostConstructprivate void initCache() {// Initializes the cache}}public Object getFromCache(Long id) {if (cache.containsKey(id))return cache.get(id);elsereturn null;}Listing 8-2 shows a snippet of code for a stateful bean. The container maintains conversationalstate, which can include heavy-duty resources such as a database connection. Because it is expensive toopen a database connection, it should be shared across calls but released when the bean is idle (orpassivated).After creating an instance of a stateful bean, the container injects the reference of a datasource tothe ds attribute. Once the injection is done, the container will call the designated @PostConstructmethod (init()), which creates a database connection. If the container happens to passivate theinstance, the close() method will be invoked (@PrePassivate). The purpose of this is to close the JDBCconnection, which holds native resources and is no longer needed during passivation. When the clientinvokes a business method on the bean, the container activates it and calls the init() method again(@PostActivate). When the client invokes the checkout() method (annotated <strong>with</strong> the @Removeannotation), the container removes the instance but first will call the close() method again(@PreDestroy).242

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!