跳至主要内容

JSF 2.2: Embrace CDI?

JSF 2.2: Embrace CDI?

CDI 1.0 is part of Java EE 6, it is the standard Dependency Injection specification for Java EE platform. But unfortunately, JSF 2.0 which is also part of Java EE 6 did not adopt CDI as its Dependency Injection/IOC container, but invented its IOC container.

Dependency injection in JSF 2.0

In the package javax.faces.bean, there are several annotations provided.
You can annotate your JSF backend bean with annotation @ManagedBean and put it in a reasonable scope( @ApplicationScoped, @RequestScoped, @SessionScoped, @ViewScoped, @NoneSopced).
@ManagedBean(name="foo")
@RequestScoped
public class FooBean{

}
The attribute name specified in the @ManagedBean can be accessed via EL in facelets views.
You can inject it in other beans via @ManagedProperty.
@ManagedBean(name="bar")
@RequestScoped
public class BarBean{
    @ManagedPropertiy("foo")
    FooBean foo;
}
In JSF 2.0, it also supports to annotate the fields with @Resource and @EJB annotations to inject Java EE resources and EJB.
@ManagedBean(name="bar")
@RequestScoped
public class BarBean{
    @Resource("")
    DataSource ds;
    
    @EJB
    HelloEJB hello;
}

CDI 1.0 and JSF 2.0

When you are using Java EE 6, you maybe have confused about the JSF IOC and CDI, we need two types of IOC mechanism in projects?
CDI provides a complete list of scopes for Java EE platform, including @ApplicationScoped, @RequestScoped, @SessionScoped, @ConversationScoped, which are provided in the package javax.enterprise.context. As you see, they are very similar with JSF scopes. The difference is JSF has a specific @ViewScoped and there is no equivalent concept in CDI, and CDI provides a @ConversationScoped which is also designated for JSF in CDI 1.0.
But due to some unknown reason, JSF EG refused to reuse CDI in Java EE 6. It was explained the JSF 2.0 features had been frozen and would not be changed, even there were some months left before Java EE 6 was released. The most reasonable explanation is that it was the result of political fight between the Java EE giants, such as Oracle, RedHat etc.
Luckily, CDI beans can be accessed through EL in faceslet views directly. And some third party projects such as JBoss Seam 3, Apache MyFaces CODI etc are born and try to fill the gap between CDI and JSF. In JBoss Seam 3, you can use CDI beans freely as JSF backend beans. Apache MyFaces CODI provides more, it mapped all JSF scopes to CDI scopes internally which allow you use JSF scopes but it is processed by CDI container, and redesigned a new powerful Conversation which support conversation group, multi conversation, nested conversation etc, and provides some extra scopes, such as @ViewAccessScoped, Window scope etc.

CDI 1.1 and JSF 2.2

In Java EE 7, the JSF specific ManagedBean specification is discontinued.
In JSF 2.2, all JSF scopes defined in JSF 2.0(in the package javax.faces.bean) should be abandoned, you can use CDI beans as JSF backend beans freely. JSF 2.2 also introduces two new CDI compatible scopes, @ViewScoped and @FlowScoped.
NOTE, the new @ViewScoped is located in the package javax.faces.view, it is a new annotation.
@FlowScoped is designated for another new feature shipped with JSF 2.2, the Faces Flow support.
Almost all JSF artifacts support @Inject now. For example, the DebugPhaseListener provided in the sample codes is a custom PhaseListener which is use for tracking the JSF request lifecycle.
public class DebugPhaseListener implements PhaseListener{
    
    @Inject Logger log;

    @Override
    public void afterPhase(PhaseEvent event) {
       log.info(" afer phase @"+ event.getPhaseId());
    }

    @Override
    public void beforePhase(PhaseEvent event) {
       log.info( " before phase @"+ event.getPhaseId());
    }

    @Override
    public PhaseId getPhaseId() {
       return PhaseId.ANY_PHASE;
    }
    
}
But unfortunately, there are some exceptions, such as JSF converter and validator still do not support @Inject, which are canceled in the last milestone before JSF 2.2 was finalized.
And many features I expected are not provided in JSF 2.2, such as bridge the JSF system events to CDI events, expose the JSF FacesContext related resources as CDI beans and allow you inject them directly instead of programmatic code.
We have to wait another 4 years?

评论

此博客中的热门博文

Build a Reactive application with Angular 5 and Spring Boot 2.0

I have created a post to describe Reactive programming supports in Spring 5 and its subprojects, all codes of this article are updated the latest Spring 5 RELEASE, check spring-reactive-sample under my Github account.
In this post, I will create a simple blog system, including:
A user can sign in and sign out.An authenticated user can create a post.An authenticated user can update a post.Only the user who has ADMIN role can delete a post.All users(including anonymous users) can view post list and post details.An authenticated user can add his comments to a certain post. The backend will be built with the latest Spring 5 reactive stack, including:
Spring Boot 2.0, at the moment the latest version is 2.0.0.M7Spring Data MongoDB supports reactive operations for MongoDBSpring Session adds reactive support for WebSessionSpring Security 5 aligns with Spring 5 reactive stack The frontend is an Angular based SPA and it will be generated by Angular CLI.
The source code is hosted on Github, …

Activating CDI in JSF 2.3

Activating CDI in JSF 2.3 When I upgraed my Java EE 7 sample to the newest Java EE 8, the first thing confused me is the CDI beans are not recoganized in Facelects template in a JSF 2.3 based web applicaiton, which is working in the development version, but in the final release version, they are always resolved as null. I filed an issue on Mojarra and discussed it with the developers from communities and the JSF experts.
According to the content of README, In a JSF 2.3 application, to activate CDI support, declaring a 2.3 versioned faces-config.xml and adding javax.faces.ENABLE_CDI_RESOLVER_CHAIN in web.xml is not enough, you have to declare @FacesConfig annotated class to enable CDI.
Here is the steps I created a workable JSF 2.3 applicatoin in Java EE 8.
Create a Java web application, this can be done easily by NetBeans IDE, or generated by Maven archetype, for exmaple.
$ mvn archetype:generate -DgroupId=com.example -DartifactId=demo -DarchetypeArtifactId=maven-archetype-w…

JSF 2.3:Websocket support

Websocket support One of the most attractive features is JSF 2.3 added native websocket support, it means you can write real-time applications with JSF and no need extra effort.
To enable websocket support, you have to add javax.faces.ENABLE_WEBSOCKET_ENDPOINT in web.xml.
<context-param> <param-name>javax.faces.ENABLE_WEBSOCKET_ENDPOINT</param-name> <param-value>true</param-value> </context-param> Hello Websocket Let's start with a simple example.
@ViewScoped@Named("helloBean") publicclassHelloBeanimplementsSerializable { privatestaticfinalLoggerLOG=Logger.getLogger(HelloBean.class.getName()); @Inject@PushPushContext helloChannel; String message; publicvoidsendMessage() { LOG.log(Level.INFO, "send push message"); this.sendPushMessage("hello"); } privatevoidsendPushMessage(Objectmessage) { helloChannel.send(""+ message +" at &…