intro.xml 9.92 KB
<?xml version='1.0' encoding="utf-8"?>
<!DOCTYPE authorgroup PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
   "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" []>
<chapter id="intro">

   <title>Introdução</title>
  
   <para>
   TODO: Apresentação do Demoiselle 2.0, tratando de forma objetiva o propósito do framework, explicando a sua estrutura e fundamentos básicos.
   </para>
   
   <para>
      So you're keen to get started writing your first bean?  Or perhaps you're skeptical, wondering what kinds of hoops
      the CDI specification will make you jump through! The good news is that you've probably already written and used
      hundreds, perhaps thousands of beans. CDI just makes it easier to actually use them to build an application!
   </para>

   <section id="bean-definition">
      <title>What is a bean?</title>

      <para>
         A bean is exactly what you think it is. Only now, it has a true identity in the container environment.
      </para>

      <para>
         Prior to Java EE 6, there was no clear definition of the term "bean" in the Java EE platform. Of course, 
         we've been calling Java classes used in web and enterprise applications "beans" for years. There were even a 
         couple of different kinds of things called "beans" in EE specifications, including EJB beans and JSF 
         managed beans. Meanwhile, other third-party frameworks such as Spring and Seam introduced their own ideas of 
         what it meant to be a "bean". What we've been missing is a common definition.
      </para>

      <para>
         Java EE 6 finally lays down that common definition in the Managed Beans specification. Managed Beans are
         defined as container-managed objects with minimal programming restrictions, otherwise known by the acronym 
         POJO (Plain Old Java Object). They support a small set of basic services, such as resource injection, lifecycle 
         callbacks and interceptors. Companion specifications, such as EJB and CDI, build on this basic model. But, 
         <emphasis>at last</emphasis>, there's a uniform concept of a bean and a lightweight component model that's
         aligned across the Java EE platform.
      </para>

      <para>
         With very few exceptions, almost every concrete Java class that has a constructor with no parameters (or a
         constructor designated with the annotation <literal>@Inject</literal>) is a bean. This includes every
         JavaBean and every EJB session bean. If you've already got some JavaBeans or session beans lying around,
         they're already beans&#8212;you won't need any additional special metadata. There's just little one thing you 
         need to do before you can start injecting them into stuff: you need to put them in an archive (a jar, or a
         Java EE module such as a war or EJB jar) that contains a special marker file: <literal>META-INF/beans.xml</literal>.
      </para>
      
      <para>
         The JavaBeans and EJBs you've been writing every day, up until now, have not been able to take advantage 
         of the new services defined by the CDI specification. But you'll be able to use every one of them with 
         CDI&#8212;allowing the container to create and destroy instances of your beans and associate them with a 
         designated context, injecting them into other beans, using them in EL expressions, specializing them with 
         qualifier annotations, even adding interceptors and decorators to them&#8212;without modifying your 
         existing code. At most, you'll need to add some annotations.
      </para>

      <para>
         Now let's see how to create your first bean that actually uses CDI.
      </para>

   </section>

   <section id="first-bean">
      <title>Getting our feet wet</title>

      <para>
         Suppose that we have two existing Java classes that we've been using for years in various applications. The
         first class parses a string into a list of sentences:
      </para>
    
      <programlisting role="JAVA"><![CDATA[public class SentenceParser {
   public List<String> parse(String text) { ... }
}]]></programlisting>

      <para>
         The second existing class is a stateless session bean front-end for an external system that is able to
         translate sentences from one language to another:
      </para>
    
      <programlisting role="JAVA"><![CDATA[@Stateless
public class SentenceTranslator implements Translator {
   public String translate(String sentence) { ... }
}]]></programlisting>

      <para>Where <literal>Translator</literal> is the EJB local interface:</para>
    
      <programlisting role="JAVA"><![CDATA[@Local
public interface Translator {
   public String translate(String sentence);
}]]></programlisting>

      <para>
         Unfortunately, we don't have a class that translates whole text documents. So let's write a bean for this job:
      </para>
    
      <programlisting role="JAVA"><![CDATA[public class TextTranslator {
   private SentenceParser sentenceParser;
   private Translator sentenceTranslator;
    
   @Inject
   TextTranslator(SentenceParser sentenceParser, Translator sentenceTranslator) {
      this.sentenceParser = sentenceParser;
      this.sentenceTranslator = sentenceTranslator;
   }
    
   public String translate(String text) {
      StringBuilder sb = new StringBuilder();
      for (String sentence: sentenceParser.parse(text)) {
          sb.append(sentenceTranslator.translate(sentence));
      }
      return sb.toString();
   }
}]]></programlisting>

      <para>
         But wait! <literal>TextTranslator</literal> does not have a constructor with no parameters! Is it still a bean?
         If you remember, a class that does not have a constructor with no parameters can still be a bean if it has a
         constructor annotated <literal>@Inject</literal>.
      </para>
        
      <para>
         As you've guessed, the <literal>@Inject</literal> annotation has something to do with dependency injection!
         <literal>@Inject</literal> may be applied to a constructor or method of a bean, and tells the container to 
         call that constructor or method when instantiating the bean. The container will inject other beans into the 
         parameters of the constructor or method.
      </para>

      <para>
         We may obtain an instance of <literal>TextTranslator</literal> by injecting it into a constructor, method
         or field of a bean, or a field or method of a Java EE component class such as a servlet. The container
         chooses the object to be injected based on the type of the injection point, not the name of the field, 
         method or parameter.
      </para>
      
      <para>
         Let's create a UI controller bean that uses field injection to obtain an instance of the
         <literal>TextTranslator</literal>, translating the text entered by a user:
      </para>
    
      <programlistingco>
         <areaspec>
            <area id="textTranslator" coords="3"/>
         </areaspec>
         <programlisting role="JAVA"><![CDATA[@Named @RequestScoped
public class TranslateController {
   @Inject TextTranslator textTranslator;

   private String inputText;
   private String translation;

   // JSF action method, perhaps
   public void translate() {
      translation = textTranslator.translate(inputText); 
   }

   public String getInputText() {
      return inputText;
   }

   public void setInputText(String text) {
      this.inputText = text;
   }

   public String getTranslation() {
      return translation;
   }
}]]></programlisting>
         <calloutlist>
            <callout arearefs="textTranslator">
               <para>
                  Field injection of <literal>TextTranslator</literal> instance
               </para>
            </callout>
         </calloutlist>
      </programlistingco>

      <tip>
         <para>
            Notice the controller bean is request-scoped and named. Since this combination is so common in web
            applications, there's a built-in annotation for it in CDI that we could have used as a shorthand. When the
            (stereotype) annotation <literal>@Model</literal> is declared on a class, it creates a request-scoped and
            named bean.
         </para>
      </tip>

      <para>
         Alternatively, we may obtain an instance of <literal>TextTranslator</literal> programmatically from an injected
         instance of <literal>Instance</literal>, parameterized with the bean type:
      </para>

      <programlisting role="JAVA"><![CDATA[@Inject Instance<TextTranslator> textTranslatorInstance;
...
public void translate() {
   textTranslatorInstance.get().translate(inputText);
}]]></programlisting> 

      <para>
         Notice that it isn't necessary to create a getter or setter method to inject one bean into another. CDI can
         access an injected field directly (even if it's private!), which sometimes helps eliminate some wasteful code. 
         The name of the field is arbitrary. It's the field's type that determines what is injected.
      </para>
    
      <para>
         At system initialization time, the container must validate that exactly one bean exists which satisfies each
         injection point. In our example, if no implementation of <literal>Translator</literal> is available&#8212;if 
         the <literal>SentenceTranslator</literal> EJB was not deployed&#8212;the container would inform us of an
         <emphasis>unsatisfied dependency</emphasis>. If more than one implementation of <literal>Translator</literal> 
         were available, the container would inform us of the <emphasis>ambiguous dependency</emphasis>.
      </para>

      <para>
         Before we get too deep in the details, let's pause and examine a bean's anatomy. What aspects of the bean are 
         significant, and what gives it its identity? Instead of just giving examples of beans, we're going to define 
         what <emphasis>makes</emphasis> something a bean.
      </para>
    
   </section>

<!--
vim:et:ts=3:sw=3:tw=120
-->
</chapter>