javax.annotation.ManagedBean

November 9, 2009 § 2 Comments

You might have heard of “managed beans” before, but chances are these will be new to you. These are not specific to JSF and not related to JMX in any way. Rather, Java EE 6 specifies Managed Beans 1.0, or lightweight components.

Managed beans are plain old java objects whose life-cycle is governed by the container (allowing for creation and destruction callbacks) and supports resource injection (and of course can themselves be injected). To define a managed bean, you simply need to annotate a class with @java.annotation.ManagedBean. You can apply the existing (JSR 250) @PostConstruct and @PreDestroy annotations to methods in that bean and inject resources using @Resources (as well as with @EJB or @WebServiceRef). Here’s a simple example :

@javax.annotation.ManagedBean
public class MessagesBean {
    @Resource
    TranslationBean localizer;

    @PostConstruct
    public void myInit() {
        System.out.println("*** Constructed!");
        // Do something useful
    }

    public String getTranslatedMessage(String message) {
        return localizer.translate(message);
    }
}

Such a class can then be deployed within a WAR, an EJB-JAR or an ACC-JAR and can be injected within another Managed Bean, a servlet, an EJB or a JSF Managed Bean using a simple @Resource MessagesBean bean; statement. Life-cycle and injection in itself is nice but it gets even better with interceptors which can also be applied to managed beans (no longer to just EJB’s) :

@Interceptors(LogInterceptor.class)
@javax.annotation.ManagedBean
public class MessagesBean {
     ...
}

Whether Managed Beans will be used directly by application developers or mostly for building higher level abstractions such as EJB’s (transactional managed beans in a sense), JAX-WS endpoints (SOAP-enabled managed beans) or JSR 299 is yet to be defined. You decide.

You can of course try all of the above in GlassFish v3.

About these ads

§ 2 Responses to javax.annotation.ManagedBean

What’s this?

You are currently reading javax.annotation.ManagedBean at Bistro! 2.0.

meta

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: