Showing posts with label CDI. Show all posts
Showing posts with label CDI. Show all posts

Tuesday, October 22, 2013

CDI Tip of the Day: Understanding Injection Techniques

diego_cervo/istockphoto.com
I just finished reading a book Understanding SCA (Service Component Architecture) that covers SCA in detail. The book is a topic for another post. I did come across a gem in the book around Dependency Injection (DI) techniques, and how to make choices around one technique over another.

The three main techniques used for Dependency Injection (DI) are constructor, setter, and field injection. There is also reflection which I will not discuss in this article.

Constructor Injection

This technique calls for injecting the objects used in our class at object instantiation. A significant advantage of this technique is that it makes all of our dependencies explicit at compile time. This also makes testing much easier since we can use testing techniques like mock objects to test. "... Constructor-based injection also enables fields to be marked as final so they cannot be inadvertently changed later on." This can also add some additional performance gains since the object are final and the compiler can optimize this. If you allow mutators for the objects injected, then this performance perk is negated since the object can not be marked final.

A disadvantage of constructor based injection is that the constructors parameter lists can become very large. I would recommend that this approach be considered for 4 parameters, or less. Four parameters can result in 16 test cases (n X n matrix). Additionally, there may be more than one constructor, and dependency injection frameworks deal with it differently. Weld currently only allows DI on one constructor.

Advantages Disadvantages
Explicit Dependencies at compile time. Constructors can become very large
Fields can be marked final Mutable fields lose final advantage
Testing can be simplified The number of parameters produces an n X n matrix of tests

Setter Injection

The next technique is using setter based injection. Typically we have an object with setters and getters where the setter is annotated for injection. This requires that our setters be public, or protected. I would recommend making them public in the absence of reasons to do otherwise. The significant advantage to setter based injection is the ability to change the injected object at runtime. If the method is public, then it can be changed by any object. This could be an advantage, or disadvantage. Also this technique is conducive to testing as well. We can inject mock objects, or use a framework like Arquillian to handle injection during testing.

The disadvantages of using setter based injection "... are two major disadvantages to setter injection. Component (Class) dependencies are dispersed across a number of setter methods, making them less obvious and increasing the verbosity of the code because a method needs to be created for every reference In addition, setter methods make references that should be immutable subject to change because the fields they are assigned cannot be declared final." The second item may not be a disadvantage if  considered closely in your design. The former represents a significant disadvantage in terms of code clarity that has been a hallmark of EE5/6/7.

Another item to consider is that the one of the best practices for developing interfaces is to avoid putting setters in them. Interface design usually only has the getter defined, the setter is an implementation detail that is left out of the contract. This prevents the client code from altering the implementation code accidentally since it should be interacting with the interface contract.

Advantages Disadvantages
Code is more testable Results in less readable code as the number of references increase.
Injection can be changed at runtime. Fields cannot be marked final
- Mutators (setters) are typically not part of the interface contract.

Field Injection

Field based injection is often used in example code found for Dependency Injection (DI) frameworks. "The major advantage of field-based injection is that it is concise." The fields may be public, private, protected, or default. They can not be marked final. This technique avoids large lists of parameters for constructors, and adding setter methods that are not part of the interface contract. The Major disadvantage is unit testing. You need to add a setters, sub-class the object, or use reflection typically. A framework like Arquillian can be used to test, but this adds additional complexity that would not be required for using constructor, or setter injection. The brevity is both an advantage and disadvantage.
Advantages Disadvantages
Concise Difficult to test
- Fields cannot be marked final

Summary

In examining the tables of advantages and disadvantages, you may come to a conclusion that Field injection may be the best choice. This would be premature. In fact, there is clearly no one technique that is better than the other. All have advantages, and disadvantages. Clearly as a developer, or architect you must decide for a given class, or set of classes which technique will meet your requirements. A lot has been said about picking a pattern, and using it consistently throughout your project. I personally find that idea bad. Comparatively, we could say it is like picking a hammer out of a toolbox and using nails everywhere. Sometimes a bolt and nut would work much better. Don't fall into the trap of consistency over what makes sense for your project.

Tuesday, September 17, 2013

JSF/CDI Tip of the Day: How to create a @Producer for JSF

I was using this code as a utility class to get the current HttpServletRequest object. I added the @Named annotation to expose it via Expression Language (EL). However, it should be noted that the #{request} is an implicit object already. You can see from the output below that they do produce the same output.

ServletRequestProducer.java


Wednesday, August 28, 2013

JSF 2.x Tip of the Day: Guice ELResolver using SLF4J Logging

Introduction

I was recently tasked with looking at some mechanisms to control logging in our JSF applications. This included a number of proof of concept ideas to see which Dependency Injection (DI) mechanisms we could use. We are currently using CDI (Weld), and OpenWebbeans in our applications. I had previously used Guice for doing DI in some other applications especially in Java SE which I found it very easy to use.

As I looked around, I found that I could not find a good example of how to use Guice with JSF 2.x. There were a number of articles from over the years for using Guice with JSF 1.2 primarily, but nothing that used some of the great enhancements to JSF 2. I also found very little on how to implement FacesWrapper to wrap ApplicationFactory, Application, and ELResolver. The exception being ELResolver code that you can find in OmniFaces.

Implementation

The implementation uses a number of techniques to inject our custom ELResolver. First we will use a FacesWrapper to wrap the ApplicationFactory. Our implementation will return a custom ApplicationWrapper implementation, that will return a custom FacesWrapper for our ELResolver. This arrangement may seem complex, but separates the concerns to allow us to refactor them as necessary.

The code for this project can be found here: jsf-guice-logger-integration

GuiceServletContextListenerImpl.java


FacesApplicationFactoryWrapper.java


FacesApplicationWrapper.java


GuiceELResolverWrapper.java


faces-config.xml

There are additional classes that do the logging that can be found in the project. The primary interest here is how to get an ELResolver implementation that will resolve our Guice injections. I hope this demonstration of JSF 2.x wrappers can show you how easy it is to implement custom wrappers including a custom ELResolver.

References

Saturday, August 03, 2013

JSF/CDI Tip of the Day: @PostConstruct Lifecycle Interceptor

SR-71
I was trying to come up with a way to inject a logger into a JSF managed bean that can be done prior to @Postconstruct. I was unsuccessful with this technique, but it was not a total loss. The examples I found on interceptors for life-cycle interception were "empty". They generally mention you can do it, but they did not show any real useful examples.

I hope to change that with this example. The example I demonstrate could be easily done with constructor injection, but in the case of a no-args constructor this may be your only opportunity to inject objects during @PostConstruct. I am going to suggest that if you want to make this functionality more general, you should use an interface and call the interface methods.

The InvocationContext will return Class<? extends T> using context.getTarget(). We can use this concept to control our injection to the object. In my case, I use setter injection on the object. Pretty cool!

The code for this example can be downloaded from here: cdi-lifecycle-interceptor-example

There are a couple of classes needed to set up our @Interceptor. The first is an interface we will call Loggable and the second is an @InterceptorBinding.

Loggable.java


This is a simple interface which we will apply to the interceptor, and to the target class that we want to intercept.

Interceptable.java


The next class we need is our @Interceptor. This code contains all of the magic we need for the target class which we are intercepting.

PostConstructInterceptor.java


As you can see we are making changes to the class after it is constructed, and before the @PostConstruct method is executed, i.e., context.proceed().

Finally, we need to have our class that we are intercepting. In this case, it is a simple @Named and @RequestScoped CDI bean.

IndexBean.java


The magic is complete, but I would recommend downloading the Maven based project to see the whole example here: cdi-lifecycle-interceptor-example

Our final output is shown here.

UUID Please?

Monday, July 09, 2012

JSF Tip of the Day: <ui:repeat /> Usage Example

Abstract

A common use case is to iterate over a collection of elements, and display them on a page. In the world of JSP, we would use a Java Standard Tag Library (JSTL) <c:forEach/>. This will work in JSF, but does have the same lifecycle as JSF which can cause issues if the data is dependent on the JSF lifecycle.
The solution is to use <ui:repeat/> to iterate over the collection. The <ui:repeat/> Facelets component is designed to work with JSF. It has the same lifecycle as the other JSF components on the page, and is a lot more flexible than the <c:forEach/> tag.

Description

The examples in this project demonstrate a number of methods to utilize the <ui:repeat/> in your own project.

Bug

There is a bug in versions of Mojarra less than 2.1.9 that the size includes the end element as per JAVASERVERFACES-2210.It was fixed as of version 2.1.9. Note: You will need to upgrade JSF libraries in GlassFish to see the corrections. Please see the release notes for Java Server Faces for upgrade procedures. The project was developed using NetBeans 7 IDE and Apache Maven. The project was tested on GlassFish 3.1.2.

The code for the project can be downloaded here: ui-repeat.zip

Code

index.xhtml



IndexBean.java


Sunday, July 08, 2012

JSF Tip of the Day: @ViewScoped and @ConversationScoped Usage

Abstract

A question that often comes up is when and where to use a particular scope in JSF. This has become even muddier with the addition of CDI support in JSF. In the upcoming release of Java EE 7, there will be even more scopes to consider. This example code demonstrates using @ViewScoped and @ConversationScoped.

Explanation

@ViewScoped

If you want to have the information on the page to update, and you are not navigating away from the page; a clear choice is the use of @ViewScoped. This is particularly true when the page is heavily dependent on AJAX. This allows partial-page submission for validation for example without losing the data contained on the page.

@ConversationScoped

@ConversationScoped scoped bean is for a long running process where there is a definite beginning and end. A perfect example is a wizard, or checking out of an online store.

The conversation begins when you click "Pay" and ends when you are given your receipt, or order information. Another example would be a complex series of wizards where there are multiple pages to complete the process. The point to keep in mind is that you have a clear bounds to start and end with.

Description

In this example code, I have a list of family members which are in different scopes depending on which example you pick. In the @ViewScoped bean you can delete people from the list and it maintains the list of changes unless you navigate away from the page. Then the list is reset back to the original values. In the @ConversationScoped bean, once you navigate to the page, a conversation begins. This will allow you to modify the list of names, and navigate to different pages and back without losing your data. Once you click on the End button, the conversation ends.

Code

The project was developed using NetBeans 7 IDE and Apache Maven. The project was tested on GlassFish 3.1.2.

The code for the project can be downloaded here: scope-examples.zip

viewscope.xhtml



conversation.xhtml



ViewScopeBean.java



ConversationBean.java


Tuesday, August 23, 2011

@PostConstruct Example Using Stateless Session Beans and CDI

There was a question posed about using @PostConstruct to initialize JSF fields from a database on the NetBeans Java EE Forum. I thought I would write a quick example of how to use @PostConstruct to initialize a list of customers, and select one to display.

This example also includes using a stateless session bean directly with the @Named annotation from Context and Dependency Injection (CDI).

All of this was accomplished using NetBeans 7.0.1.

Index.java



A copy of the project can be downloaded here: postconstruct.zip

Popular Posts