Enterprise Java without EJBs (but with CDI and MyFaces CODI)

At the W-JAX 2010 Peter Rossbach (Apache Tomcat Committer and freelancer) and I spoke about JavaEE 6 and particular the new ‘lightweight’ possibilities that are available with the WebProfile from JavaEE 6. We covered the following technologies in our talk:

  • JavaServer Faces 2.0
  • CDI
  • EJB 3.1 lite
  • JPA 2.0

We showed a demo of the integration of these tools with Apache Tomcat 7. Was good, so far….

..but why not doing it without EJB… ?

One of the above technologies is really really powerful: CDI (Contexts and Dependency Injection for the Java(tm) EE platform). With CDI it is even possible to replace EJB. All you need is an annotation (something like Spring’s @Transactional) and an Interceptor that kicks in the transaction handling for annotated methods. But… do I have to write all that stuff? The answer is NO!

The Apache MyFaces CODI project offers this as part of it’s 0.9.0 release (and way more cool CDI extensions, like new scopes etc). Don’t worry about the ‘low’ release number. It’s pretty stable but there maybe the change that there are a few changes on the API and this would be a PITA for a 1.x release…

The stack for an application like that would basically contain: JSF2, CDI, JPA. That’s it. All components are managed (including their scoping) via CDI. The JSF ‘Controller’ Bean (behind a page) uses @Inject to get access to a Service implementation:

@Named
@RequestScoped
public class SomeFacesController
{
@Inject private SomeService service;
...
}

Inside of the service implementation the @Inject is used in a similar way: The CDI Container injects our DAO object:

public class SomeServerImpl implements SomeService
{
@Inject
private SomeDao dao;
...
}

The interesting part is happening here, inside of the DAO. That’s where we use the @Transactional annotation from CODI:

...
import org.apache.myfaces.extensions.cdi.jpa.api.Transactional;

public class SomeDao
{
@PersistenceContext
protected EntityManager em;

@Transactional
public void delete(SomeObject entity)
{
em.remove(em.merge(entity));
}
...

That’s all! The stack is really really cool and there is no need for an EJB container. The Service uses a JPA-based DAO, which is uses the CODI Interceptor for the transaction handling.

I wrote two demos to use CODI + CDI with JSF (2.0 and 1.2). All you need to do to get them running is the execution of Maven (via ‘mvn’).

Have you!

Using CDI Scopes with Spring 3

With the advent of Spring 3 the framework now supports the Java Injection standard (JSR 330). However, unfortunately, they do not support the scoping, which is introduced in Java EE 6,through the CDI specification (JSR 299).

Now the big difference between a JSF “managed bean” in Java EE 6 and Spring is that they basically use a different scoping (JavaEE vs. Spring)!

However, the remaining parts are exactly the same, in both worlds:

  • @Named and Qualifiers for for naming and type-safety…
  • @Inject to identify “injection points” for dependencies/resources…

During our JAX 2010, Lars Röwekamp and I showed how enable the Spring Framework to understand the CDI scopes, such as @RequestScoped or @SessionScoped.

Before that, I spoke to Juergen Hoeller on the JAX conference, and he explained me the underlying mechanism and how something like that could be easily done!

The Spring Framework uses a ScopeMetadataResolver to resolve the SPRING-based scopes of the bean definitions. To actually enable the CDI scopes I “decorated” their default implementation, the AnnotationScopeMetadataResolver class:

public class CdiScopeMetadataResolver
extends AnnotationScopeMetadataResolver
{
 @Override
 public ScopeMetadata resolveScopeMetadata(BeanDefinition definition)
 {
 ScopeMetadata metadata = new ScopeMetadata();
 if (definition instanceof AnnotatedBeanDefinition)
 {
 AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
 Set<String> annotationTypes = annDef.getMetadata().getAnnotationTypes();

 if (annotationTypes.contains(
 javax.enterprise.context.RequestScoped.class.getName())
 )
 {
 metadata.setScopeName("request");
 }
 else if (annotationTypes.contains(
 javax.enterprise.context.SessionScoped.class.getName())
 )
 {
 metadata.setScopeName("session");
 }

...
//more...
//
 else
 {
 // do the regular Spring stuff..
 return super.resolveScopeMetadata(definition);
 }
 }
 return metadata;
 }
}

The CdiScopeMetadataResolver class scans the actual Spring beans and checks if the CDI
scope annotations are declared. If they are present we simply map them to their corresponding
Spring scopes!

So the trick is that you annotate them with CDI, but under the hood they are Spring scopes!

Now in your Spring configuration you simply enable it like:

...
 <context:component-scan
base-package="my.packages..."
scope-resolver="...CdiScopeMetadataResolver" />
...

Now you are able to define your Spring/JSF beans with 100% JavaEE-based annotations.

UPDATE: I published the code of this class to github.

Enjoy!

Spring 3.0 and JSR 330: Using @Named

The Spring 3.x release comes with a build-in support for the JSR 330, called “at inject” (or Dependency Injection for Java). So it is now possible to use these annotation as an alternative for the @Autowired et al.

The benefit of the JSR330 is that it is supported in different environments:

  • JavaEE 6
  • Spring 3.0
  • Guice 2.0

So the dependency base for all these frameworks is now the same, with some small differences. Using JSR330 with Spring is actually very simple. In your application-context.xml file you need to have the <context:component-scan> element, like:

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
...>

<context:component-scan base-package="net.wessendorf" />

</beans>

Now the annoations can be used in your classes:

package net.wessendorf.spring;

import java.io.Serializable;
import javax.inject.Named;
import org.springframework.context.annotation.Scope;

@Named("mybean")
@Scope("session")
public class SimpleBean implements Serializable
{
...
}

The above snippet defines a session-scoped bean, which has the name “mybean”. So when using the SpringBeanFacesELResolver class (for JSF), your XHTML page can easily use the bean in it…

In CDI there are similar annotations for scoping, like RequestScoped, SessionScoped or ApplicationScoped. Spring has just one Scope annotation which itself takes the actual scope as its parameter. CDI also has a convenience annotation which combines @Named and @RequestScoped, and you can create similar ones, as extensions.

Of course this is possible with Spring 3.0 as well:

package net.wessendorf.spring.stereotype;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.inject.Named;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Named
@Scope("request")
@Component
@Target( { TYPE, METHOD, FIELD })
@Retention(RUNTIME)
@Documented
public @interface Model
{ }

The interesting part is the @Named, which makes the name available, the @Scoped, which is set to request on your new @Model annotation and the @Component to mark the annotated class a as “Spring component”. Now instead of always adding @Named and @Scope(“request”) you could simply use the new @Model:

@net.wessendorf.spring.stereotype.Model
public class TesterBean
{
...
}

Now the above TesterBean can be resolved as “testerBean” in your JSF XHTML page.

Have fun!

Demo of Apache MyFaces 2 and OpenWebBeans

Recently the Apache MyFaces project released its second beta release and yesterday the Apache OpenWebBeans project released its M4 release.

These are great milestones in the direction of JavaEE at Apache!

A few month ago Bernd Bohmann and I were giving a JSF2 + X presentation in Muenster, at the JUG. The presentation was great and we showed a lot of cool features of JSF2 and CDI. The big plus was that we were Apache projects (MyFaces and OWB), which we build from the trunk. Now since there are these important milestones, I was able to actually make the demo project available under my “facesgoodies” demo/kickstart project.

Get the source of the Maven project from here.

Once you extracted the source, just run “mvn” and Maven downloads all you need!

Enjoy!

combining CDI producer methods with EL

CDI’s Producer methods are nice to expose any sort of class (e.g. legacy or 3rd party (JDK)). Combining the @Produces with the @Named you can reuse the result in your XHTML JSF page.

Some Java code:

...
@Produces @Named public MyBean getMyBeanImpl()
{
....
return someBean;
}

Now the XHTML can have something like:

...
<h:outputText value="#{myBeanImpl.someOfItsProperties}" />
...

If you want, you can use the @Named with a named value (e.g. @Named(“fooBar”)). Now the fooBar also is required by the EL.

Pretty nice!

Dependency Injection the JSR 330 way

Dependency Injection is not new! There have been several ways of doing DI in your Java application. The idea behind them is well understood, but the actual realization is slightly different: XML files vs Java annotation/classes etc… That can become a pretty religious discussion :-)

With the on-going progress of the “WebBeans” specification, which defines (or defined) some common Java DI API, it was clear that there is need for a more abstract way. The new “at inject” (or Dependency Injection for Java) standard, JSR 330, was born. WebBeans has been renamed to Contexts and Dependency Injection for the Java EE platform (short: CDI). CDI now also leverages the “at inject” API, specified in JSR 330. The main idea behind this new JSR was driven by Ex-Google-Fellow Bob Lee, how is responsible for the Google-Guice DI framework.

Now, using the tiny JSR 330 API is pretty simple. First you define an injection point in a class, which wants to use a concrete implementation of a common (business…) service:

// injection-point; no get/set needed...
@Inject private BusinessService service;

Now, you need to provide an implementation:

...
public class DefaultBusinessService implements BusinessService
{
...
}
...

If you have more versions of this service, you have to create a Qualifier annotation:

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.inject.Qualifier;

@Qualifier
@Target( { TYPE, METHOD, FIELD })
@Retention(RUNTIME)
public @interface FancyService
{
}

You use the Qualifier to inject a more meaningful implementation of the service:

@Inject @FancyService private BusinessService fancyService;

Now the question that comes up is what implementation of this JSR should I use ?

The ultimate suggestion would be, especially when running in the Java EE world, to use an implementation of the JSR 299. There are currently three options for that:

But what if I am not in a JavaEE container? When I am writing a tiny, small Java SE application ? The good news is here that Google Guice implements the JSR-330 as well. This is not a big surprise, since one of the guys behind the JSR-330 is Bob Lee, from Google-Guice. As a matter of fact, there is a wiki page, which acts a guide on using 330 and Guice.

Not only 299 implementations or Google Guice are supporting the unified API for Java Dependency Injection. The popular Spring framework, starting with its 3.0.x version, also has support for it!

The benefit of the wide support is that you only need to learn a simple API, which can be re-used in different environments. On Java EE containers the obligatory choice is a 299 implementation, such as Apache OpenWebBeans or JBoss Weld.But outside of the “webapplication world”, you can use the API and Guice or Spring as the implementation of the standard. Sure, most JSR-299 containers run in a vanilla JavaSE environment as well.

Summary: The API is simple and easy to use. You nail yourself to no specific platform by using/learning this API. Next blogs will be more specific to JSR-299 implementation to see what that spec adss on-top of it, such is a the producer methods., which offers a nice way to expose legacy (or vanilla JDK) classes as a injectable component.

Extensions for CDI

The JSRs 299/330 are pretty interesting as they offer a nice way to use its flexible structure to easily add new features. For instance inside of the Apache implementation (Apache OpenWebBeans) there is already some extension that adds decent support for the JSF2.0 @ViewScoped annotation. The commit shows that the implementation of this wasn’t that of a big deal.

The Apache MyFaces and Apache OWB communities put together a wiki page to discuss more extensions. The endresult of this effort will be (most-likely) a new subproject of the “Apache MyFaces Extension” project. Note: This project currently hosts ExtVal (Validation-Framework) and ExtScripting (support for dynamic languages, such as Groovy).

299/330 offers a nice tool to also create convenience annotations. One of them, the @Model, is already part of the CDI offerings. This annotation basically combines the @Named and @RequestScoped annotations. Something like that can be done for different scopes, such as @ApplicationScoped, @SessionScoped or @ViewScoped.

This is pretty trival:

package net.wessendorf.enterprise.inject;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Stereotype;
import javax.inject.Named;

@Named
@SessionScoped
@Stereotype
@Target( { TYPE, METHOD, FIELD })
@Retention(RUNTIME)
@Documented
public @interface SessionModel
{
}

Put stuff like that into a tiny little JAR and reuse it on all your project; Simple and fast done!

On your beans this particular annotation goes along like this:

package net.wessendorf.facesgoodies;

import java.io.Serializable;

import net.wessendorf.enterprise.inject.SessionModel;

@SessionModel
public class SomeRandomBean implements Serializable
{
...
}

So get a change to checkout Apache OWB and give it a shot! Pretty good implementation, so far!

JSF 2 and CDI – a nice combo!

In JSF 2.0 there is (optional) support for annotating JSF Managed beans, via the Faces Managed Bean Annotation Specification. Both Apache MyFaces and the SUN RI implement this specification.

With the advent of these two JSRs:

There is an ongoing discussion about the right annotation for the “JSF beans”.

I agree that a JSF 2.0 application should avoid using the @ManagedBean annotation. I prefer using the stuff that 299/330 are offering. The good news is that even Spring (in Version 3.0) does actually support the @inject specification (e.g. @Named).

Using the two specifications, a simple bean could look like:

...
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@Named
@RequestScoped
public class HelloWorldBean
{
...
}
...

For CDI there is a neat convenience annotation (@Model) that combines the two above (@Named and @RequestScoped)!

Too bad that Spring does not support CDI (JSR 299), so the @Model is not usable there… However, making something on your own (e.g. @SpringModelBean) is not hard, as you just have to combine the @Named and the @Scope(“request”) annotation, from Spring…

UPDATE: Enabling the CDI/299 Scopes in Spring is pretty simple.

One concern maybe that 299 is only usable inside of a fullblown Java EE 6 container, like Glassfish3. But that is not the case. The implementations of the 299 specification from Apache(OpenWebBeans) and JBoss (Weld) are offering support for Servlet Containers, like Tomcat.

I added a new (very) simple HelloWorld that combines CDI(299/330) and JSF 2.0 to my FacesGoodies project. The source is located here. For the implementations I picked Apache MyFaces 2.0 (the first alpha release is out; a beta is coming soon) and Apache OpenWebBean (which recently left the Apache Incubator). The combination of these two standards really matches very well. I will add more complex demos to FacesGoodies soon, but this (trivial) HelloWorld demo is just a starting point.
Note: Currently you have to build the OpenWebBeans stuff, to have the latest greatest fixes from the trunk (or, use the M3 release from the incubator repository).

Another benefit is, as my demo uses the JettyMavenPlugin, with CDI you can use the jetty:run goal. The annotations for the JSF managed bean facility do require jetty:run-exploded, which is kinda odd… See… another reason to use CDI with JSF 2.0 :-)

Apache offers great support for these with its MyFaces and OpenWebBeans project! Check em out!

HINT: You need to build Apache OpenWebBeans in order to run this example. Do the SVN checkout from this location. And run mvn install in its root-folder!

JBoss’ WebBeans and TCK

By accident, I noticed this link on the Seam website. It talks about WebBeans. No, it doesn’t only talk about WebBeans and the relationship to Seam. It does much more… it contains a link to the source code… Not a big deal… But! I am really happy to see that WebBeans is developed under ASL 2.0, by JBoss/Red Hat.

Even better, the page says that the TCK (not yet there) will also be licensed under ASL 2.0. Which is really great news! As far as I know, the only TCK that is ASL 2.0 based is the one from JDO.

Well done, JBoss!