Book Image

JBoss Weld CDI for Java Platform

By : Kenneth Finnigan
Book Image

JBoss Weld CDI for Java Platform

By: Kenneth Finnigan

Overview of this book

CDI simplifies dependency injection for modern application developers by taking advantage of Java annotations and moving away from complex XML, while at the same time providing an extensible and powerful programming model. "JBoss Weld CDI for Java Platform" is a practical guide to CDI's dependency injection concepts using clear and easy-to-follow examples. This will help you take advantage of the power behind CDI, as well as providing a firm understanding of how to use it within your applications. "JBoss Weld CDI for Java Platform" covers all the major aspects of CDI, breaking it down into understandable pieces. This book will take you through many examples of how these concepts can be utilized, helping you get up and running quickly and painlessly. "JBoss Weld CDI for Java Platform" gives you an insight into the different scopes provided by CDI and the use cases for which each has been designed. You will learn everything about dependency injection, scopes, events, producers, and more from JBoss Weld CDI, as well as how producers can create new beans for consumption within your application. You will also learn how to build a real world application with CDI using JSF and AngularJS for different web interfaces.
Table of Contents (17 chapters)
JBoss Weld CDI for Java Platform
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Injection into producer methods


Coming back to our producer method at the start of the chapter, there is one problem that we may experience as the code is currently written. Creating FictionSearch and NonFictionSearch with the Java new operator means that they are not eligible for dependency injection and cannot have interceptors.

Both of those restrictions may be acceptable to our application, but if they aren't then we can use dependency injection into the producer method to ensure that we are using beans controlled by Weld. The producer would now be as follows:

@Produces
@Preferred
@SessionScoped
public BookSearch getSearch(FictionSearch fs, NonFictionSearch nfs) {

  switch (searchType) {
    case FICTION:
      return fs;
    case NONFICTION:
      return nfs;
    default:
      return null;
  }
}

In our example, FictionSearch and NonFictionSearch are both @RequestScoped beans; so what does that mean for our producer as we're producing a bean into @SessionScoped? Our producer method has...