SeamFramework.orgCommunity Documentation
The Web Beans (JSR-299) specification defines a set of services for the Java EE environment that makes applications much easier to develop. Web Beans layers an enhanced lifecycle and interaction model over existing Java component types including JavaBeans and Enterprise Java Beans. As a complement to the traditional Java EE programming model, the Web Beans services provide:
an improved lifecycle for stateful components, bound to well-defined contexts,
a typesafe approach to dependency injection,
interaction via an event notification facility, and
a better approach to binding interceptors to components, along with a new kind of interceptor, called a decorator, that is more appropriate for use in solving business problems.
Dependency injection, together with contextual lifecycle management, saves the user of an unfamiliar API from having to ask and answer the following questions:
what is the lifecycle of this object?
how many simultaneous clients can it have?
is it multithreaded?
where can I get one from?
do I need to explicitly destroy it?
where should I keep my reference to it when I'm not using it directly?
how can I add an indirection layer, so that the implementation of this object can vary at deployment time?
how should I go about sharing this object between other objects?
A Web Bean specifies only the type and semantics of other Web Beans it depends upon. It need not be aware of the actual lifecycle, concrete implementation, threading model or other clients of any Web Bean it depends upon. Even better, the concrete implementation, lifecycle and threading model of a Web Bean it depends upon may vary according to the deployment scenario, without affecting any client.
Events, interceptors and decorators enhance the loose-coupling that is inherent in this model:
event notifications decouple event producers from event consumers,
interceptors decouple technical concerns from business logic, and
decorators allow business concerns to be compartmentalized.
Most importantly, Web Beans provides all these facilities in a typesafe way. Web Beans never uses string-based identifiers to determine how collaborating objects fit together. And XML, though it remains an option, is rarely used. Instead, Web Beans uses the typing information that is already available in the Java object model, together with a new pattern, called binding annotations, to wire together Web Beans, their dependencies, their interceptors and decorators and their event consumers.
The Web Beans services are general and apply to the following types of components that exist in the Java EE environment:
all JavaBeans,
all EJBs, and
all Servlets.
Web Beans even provides the necessary integration points so that other kinds of components defined by future Java EE specifications or by non-standard frameworks may be cleanly integrated with Web Beans, take advantage of the Web Beans services, and interact with any other kind of Web Bean.
Web Beans was influenced by a number of existing Java frameworks, including Seam, Guice and Spring. However, Web Beans has its own very distinct character: more typesafe than Seam, more stateful and less XML-centric than Spring, more web and enterprise-application capable than Guice.
Most importantly, Web Beans is a JCP standard that integrates cleanly with Java EE, and with any Java SE environment where embeddable EJB Lite is available.
Sommario
Non vedi l'ora di iniziare a scrivere il primo Web Beans? O forse sei un pò scettico e ti domandi in quali cerchi ti farà saltare dentro la specifica Web Beans! La buona notizia è che probabilmente hai già scritto e usato centinaia, forse migliaia di Web Beans. Si potrebbe addirittura non ricordare il primo Web Bean scritto.
Con alcune eccezioni molto speciali, ogni classe Java con un costruttore che non accetta paramentri è un Web Bean. Questo include ogni JavaBean. Inoltre, ogni session bean di stile EJB3 è un Web Bean. Sicuramente i JavaBean e gli EJB3 che si sono sempre scritti non erano in grado di sfruttare i nuovi servizi definiti dalla specifica Web Beans, ma si sarà presto in grado di usare ciascuno di essi come Web Beaniniettandoli in altri Web Beans, configurandoli tramite strumenti di configurazione XML Web Bean, e perfino aggiungendo a loro interceptor e decoratorisenza toccare il codice esistente.
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:
public class SentenceParser {
public List<String
> parse(String text) { ... }
}
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:
@Stateless
public class SentenceTranslator implements Translator {
public String translate(String sentence) { ... }
}
Where Translator
is the local interface:
@Local
public interface Translator {
public String translate(String sentence);
}
Unfortunately, we don't have a preexisting class that translates whole text documents. So let's write a Web Bean that does this job:
public class TextTranslator {
private SentenceParser sentenceParser;
private Translator sentenceTranslator;
@Initializer
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();
}
}
We may obtain an instance of TextTranslator
by injecting it into a Web Bean, Servlet or EJB:
@Initializer
public setTextTranslator(TextTranslator textTranslator) {
this.textTranslator = textTranslator;
}
Alternatively, we may obtain an instance by directly calling a method of the Web Bean manager:
TextTranslator tt = manager.getInstanceByType(TextTranslator.class);
But wait: TextTranslator
does not have a constructor with no parameters! Is it still a Web Bean? Well, a class that does not have a constructor with no parameters can still be a Web Bean if it has a constructor annotated @Initializer
.
As you've guessed, the @Initializer
annotation has something to do with dependency injection! @Initializer
may be applied to a constructor or method of a Web Bean, and tells the Web Bean manager to call that constructor or method when instantiating the Web Bean. The Web Bean manager will inject other Web Beans to the parameters of the constructor or method.
At system initialization time, the Web Bean manager must validate that exactly one Web Bean exists which satisfies each injection point. In our example, if no implementation of Translator
availableif the SentenceTranslator
EJB was not deployedthe Web Bean manager would throw an UnsatisfiedDependencyException
. If more than one implementation of Translator
was available, the Web Bean manager would throw an AmbiguousDependencyException
.
So what, exactly, is a Web Bean?
A Web Bean is an application class that contains business logic. A Web Bean may be called directly from Java code, or it may be invoked via Unified EL. A Web Bean may access transactional resources. Dependencies between Web Beans are managed automatically by the Web Bean manager. Most Web Beans are stateful and contextual. The lifecycle of a Web Bean is always managed by the Web Bean manager.
Let's back up a second. What does it really mean to be "contextual"? Since Web Beans may be stateful, it matters which bean instance I have. Unlike a stateless component model (for example, stateless session beans) or a singleton component model (such as servlets, or singleton beans), different clients of a Web Bean see the Web Bean in different states. The client-visible state depends upon which instance of the Web Bean the client has a reference to.
However, like a stateless or singleton model, but unlike stateful session beans, the client does not control the lifecycle of the instance by explicitly creating and destroying it. Instead, the scope of the Web Bean determines:
the lifecycle of each instance of the Web Bean and
which clients share a reference to a particular instance of the Web Bean.
For a given thread in a Web Beans application, there may be an active context associated with the scope of the Web Bean. This context may be unique to the thread (for example, if the Web Bean is request scoped), or it may be shared with certain other threads (for example, if the Web Bean is session scoped) or even all other threads (if it is application scoped).
Clients (for example, other Web Beans) executing in the same context will see the same instance of the Web Bean. But clients in a different context will see a different instance.
One great advantage of the contextual model is that it allows stateful Web Beans to be treated like services! The client need not concern itself with managing the lifecycle of the Web Bean it is using, nor does it even need to know what that lifecyle is. Web Beans interact by passing messages, and the Web Bean implementations define the lifecycle of their own state. The Web Beans are loosely coupled because:
they interact via well-defined public APIs
their lifecycles are completely decoupled
We can replace one Web Bean with a different Web Bean that implements the same API and has a different lifecycle (a different scope) without affecting the other Web Bean implementation. In fact, Web Beans defines a sophisticated facility for overriding Web Bean implementations at deployment time, as we will see in Sezione 4.2, «Deployment types».
Note that not all clients of a Web Bean are Web Beans. Other objects such as Servlets or Message-Driven Beanswhich are by nature not injectable, contextual objectsmay also obtain references to Web Beans by injection.
Enough hand-waving. More formally, according to the spec:
A Web Bean comprises:
A (nonempty) set of API types
A (nonempty) set of binding annotation types
A scope
A deployment type
Optionally, a Web Bean name
A set of interceptor binding types
A Web Bean implementation
Let's see what some of these terms mean, to the Web Bean developer.
Web Beans usually acquire references to other Web Beans via dependency injection. Any injected attribute specifies a "contract" that must be satisfied by the Web Bean to be injected. The contract is:
an API type, together with
a set of binding types.
An API is a user-defined class or interface. (If the Web Bean is an EJB session bean, the API type is the @Local
interface or bean-class local view). A binding type represents some client-visible semantic that is satisfied by some implementations of the API and not by others.
Binding types are represented by user-defined annotations that are themselves annotated @BindingType
. For example, the following injection point has API type PaymentProcessor
and binding type @CreditCard
:
@CreditCard PaymentProcessor paymentProcessor
If no binding type is explicitly specified at an injection point, the default binding type @Current
is assumed.
For each injection point, the Web Bean manager searches for a Web Bean which satisfies the contract (implements the API, and has all the binding types), and injects that Web Bean.
The following Web Bean has the binding type @CreditCard
and implements the API type PaymentProcessor
. It could therefore be injected to the example injection point:
@CreditCard
public class CreditCardPaymentProcessor
implements PaymentProcessor { ... }
If a Web Bean does not explicitly specify a set of binding types, it has exactly one binding type: the default binding type @Current
.
Web Beans defines a sophisticated but intuitive resolution algorithm that helps the container decide what to do if there is more than one Web Bean that satisfies a particular contract. We'll get into the details in Capitolo 4, Dependency injection.
Deployment types let us classify our Web Beans by deployment scenario. A deployment type is an annotation that represents a particular deployment scenario, for example @Mock
, @Staging
or @AustralianTaxLaw
. We apply the annotation to Web Beans which should be deployed in that scenario. A deployment type allows a whole set of Web Beans to be conditionally deployed, with a just single line of configuration.
Many Web Beans just use the default deployment type @Production
, in which case no deployment type need be explicitly specified. All three Web Bean in our example have the deployment type @Production
.
In a testing environment, we might want to replace the SentenceTranslator
Web Bean with a "mock object":
@Mock
public class MockSentenceTranslator implements Translator {
public String translate(String sentence) {
return "Lorem ipsum dolor sit amet";
}
}
We would enable the deployment type @Mock
in our testing environment, to indicate that MockSentenceTranslator
and any other Web Bean annotated @Mock
should be used.
We'll talk more about this unique and powerful feature in Sezione 4.2, «Deployment types».
The scope defines the lifecycle and visibility of instances of the Web Bean. The Web Beans context model is extensible, accommodating arbitrary scopes. However, certain important scopes are built-in to the specification, and provided by the Web Bean manager. A scope is represented by an annotation type.
For example, any web application may have session scoped Web Beans:
@SessionScoped
public class ShoppingCart { ... }
An instance of a session scoped Web Bean is bound to a user session and is shared by all requests that execute in the context of that session.
By default, Web Beans belong to a special scope called the dependent pseudo-scope. Web Beans with this scope are pure dependent objects of the object into which they are injected, and their lifecycle is bound to the lifecycle of that object.
We'll talk more about scopes in Capitolo 5, Scopes and contexts.
A Web Bean may have a name, allowing it to be used in Unified EL expressions. It's easy to specify the name of a Web Bean:
@SessionScoped @Named("cart")
public class ShoppingCart { ... }
Now we can easily use the Web Bean in any JSF or JSP page:
<h:dataTable value="#{cart.lineItems}" var="item"> .... </h:dataTable >
It's even easier to just let the name be defaulted by the Web Bean manager:
@SessionScoped @Named
public class ShoppingCart { ... }
In this case, the name defaults to shoppingCart
the unqualified class name, with the first character changed to lowercase.
Web Beans supports the interceptor functionality defined by EJB 3, not only for EJB beans, but also for plain Java classes. In addition, Web Beans provides a new approach to binding interceptors to EJB beans and other Web Beans.
It remains possible to directly specify the interceptor class via use of the @Interceptors
annotation:
@SessionScoped
@Interceptors(TransactionInterceptor.class)
public class ShoppingCart { ... }
However, it is more elegant, and better practice, to indirect the interceptor binding through an interceptor binding type:
@SessionScoped @Transactional
public class ShoppingCart { ... }
We'll discuss Web Beans interceptors and decorators in Capitolo 7, Gli interceptor and Capitolo 8, Decoratori.
We've already seen that JavaBeans, EJBs and some other Java classes can be Web Beans. But exactly what kinds of objects are Web Beans?
The Web Beans specification says that a concrete Java class is a simple Web Bean if:
it is not an EE container-managed component, like an EJB, a Servlet or a JPA entity,
it is not a non-static static inner class,
it is not a parameterized type, and
it has a constructor with no parameters, or a constructor annotated @Initializer
.
Thus, almost every JavaBean is a simple Web Bean.
Every interface implemented directly or indirectly by a simple Web Bean is an API type of the simple Web Bean. The class and its superclasses are also API types.
The specification says that all EJB 3-style session and singleton beans are enterprise Web Beans. Message driven beans are not Web Beanssince they are not intended to be injected into other objectsbut they can take advantage of most of the functionality of Web Beans, including dependency injection and interceptors.
Every local interface of an enterprise Web Bean that does not have a wildcard type parameter or type variable, and every one of its superinterfaces, is an API type of the enterprise Web Bean. If the EJB bean has a bean class local view, the bean class, and every one of its superclasses, is also an API type.
Stateful session beans should declare a remove method with no parameters or a remove method annotated @Destructor
. The Web Bean manager calls this method to destroy the stateful session bean instance at the end of its lifecycle. This method is called the destructor method of the enterprise Web Bean.
@Stateful @SessionScoped
public class ShoppingCart {
...
@Remove
public void destroy() {}
}
So when should we use an enterprise Web Bean instead of a simple Web Bean? Well, whenever we need the advanced enterprise services offered by EJB, such as:
method-level transaction management and security,
concurrency management,
instance-level passivation for stateful session beans and instance-pooling for stateless session beans,
remote and web service invocation, and
timers and asynchronous methods,
we should use an enterprise Web Bean. When we don't need any of these things, a simple Web Bean will serve just fine.
Many Web Beans (including any session or application scoped Web Bean) are available for concurrent access. Therefore, the concurrency management provided by EJB 3.1 is especially useful. Most session and application scoped Web Beans should be EJBs.
Web Beans which hold references to heavy-weight resources, or hold a lot of internal state benefit from the advanced container-managed lifecycle defined by the EJB @Stateless
/@Stateful
/@Singleton
model, with its support for passivation and instance pooling.
Finally, it's usually obvious when method-level transaction management, method-level security, timers, remote methods or asynchronous methods are needed.
It's usually easy to start with simple Web Bean, and then turn it into an EJB, just by adding an annotation: @Stateless
, @Stateful
or @Singleton
.
A producer method is a method that is called by the Web Bean manager to obtain an instance of the Web Bean when no instance exists in the current context. A producer method lets the application take full control of the instantiation process, instead of leaving instantiation to the Web Bean manager. For example:
@ApplicationScoped
public class Generator {
private Random random = new Random( System.currentTimeMillis() );
@Produces @Random int next() {
return random.nextInt(100);
}
}
The result of a producer method is injected just like any other Web Bean.
@Random int randomNumber
The method return type and all interfaces it extends/implements directly or indirectly are API types of the producer method. If the return type is a class, all superclasses are also API types.
Some producer methods return objects that require explicit destruction:
@Produces @RequestScoped Connection connect(User user) {
return createConnection( user.getId(), user.getPassword() );
}
These producer methods may define matching disposal methods:
void close(@Disposes Connection connection) {
connection.close();
}
This disposal method is called automatically by the Web Bean manager at the end of the request.
We'll talk much more about producer methods in Capitolo 6, Metodi produttori.
Finally, a JMS queue or topic can be a Web Bean. Web Beans relieves the developer from the tedium of managing the lifecycles of all the various JMS objects required to send messages to queues and topics. We'll discuss JMS endpoints in Sezione 13.4, «Endpoint JMS».
Illustriamo queste idee con un esempio completo. Implementiamo il login/logout dell'utente per un'applicazione che utilizza JSF. Innanzitutto definiamo un Web Bean che mantenga username e password digitati durante il login:
@Named @RequestScoped
public class Credentials {
private String username;
private String password;
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
Questo Web Bean è associato al login all'interno della seguente form JSF:
<h:form>
<h:panelGrid columns="2" rendered="#{!login.loggedIn}">
<h:outputLabel for="username"
>Username:</h:outputLabel>
<h:inputText id="username" value="#{credentials.username}"/>
<h:outputLabel for="password"
>Password:</h:outputLabel>
<h:inputText id="password" value="#{credentials.password}"/>
</h:panelGrid>
<h:commandButton value="Login" action="#{login.login}" rendered="#{!login.loggedIn}"/>
<h:commandButton value="Logout" acion="#{login.logout}" rendered="#{login.loggedIn}"/>
</h:form
>
Il vero lavoro è fatto da un Web Bean con scope di sessione che mantiene le informazioni sull'utente correntemente loggato ed espone l'entity User
agli altri Web Beans:
@SessionScoped @Named
public class Login {
@Current Credentials credentials;
@PersistenceContext EntityManager userDatabase;
private User user;
public void login() {
List<User
> results = userDatabase.createQuery(
"select u from User u where u.username=:username and u.password=:password")
.setParameter("username", credentials.getUsername())
.setParameter("password", credentials.getPassword())
.getResultList();
if ( !results.isEmpty() ) {
user = results.get(0);
}
}
public void logout() {
user = null;
}
public boolean isLoggedIn() {
return user!=null;
}
@Produces @LoggedIn User getCurrentUser() {
return user;
}
}
@LoggedIn
è un'annotazione di binding:
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD})
@BindingType
public @interface LoggedIn {}
Ora qualsiasi altro Web Bean può facilmente iniettare l'utente corrente:
public class DocumentEditor {
@Current Document document;
@LoggedIn User currentUser;
@PersistenceContext EntityManager docDatabase;
public void save() {
document.setCreatedBy(currentUser);
docDatabase.persist(document);
}
}
Quest'esempio è un assaggio del modello di programmazione con Web Bean. Nel prossimo capitolo esploreremo la dependency injection dei Web Bean con maggior profondità.
The Web Beans Reference Implementation is being developed at the Seam project. You can download the latest developer release of Web Beans from the the downloads page.
The Web Beans RI comes with a two deployable example applications: webbeans-numberguess
, a war example, containing only simple beans, and webbeans-translator
an ear example, containing enterprise beans. To run the examples you'll need the following:
the latest release of the Web Beans RI,
JBoss AS 5.0.0.GA, and
Ant 1.7.0.
Currently, the Web Beans RI only runs on JBoss Application Server 5. You'll need to download JBoss AS 5.0.0.GA from jboss.org, and unzip it. For example:
$ cd /Applications $ unzip ~/jboss-5.0.0.GA.zip
Next, download the Web Beans RI from seamframework.org, and unzip it. For example
$ cd ~/ $ unzip ~/webbeans-1.0.0.ALPHA1.zip
Next, we need to tell Web Beans where JBoss is located. Edit jboss-as/build.properties
and set the jboss.home
property. For example:
jboss.home=/Applications/jboss-5.0.0.GA
As Web Beans is a new piece of software, you need to update JBoss AS to run the Web Beans RI. Future versions of JBoss AS will include these updates, and this step won't be necessary.
Currently, two updates are needed. Firstly, a new deployer, webbeans.deployer
is added. This adds supports for Web Bean archives to JBoss AS, and allows the Web Beans RI to query the EJB3 container and discover which EJBs are installed in your application. Secondly, an update to JBoss EJB3 is needed.
To install the update, you'll need Ant 1.7.0 installed, and the ANT_HOME
environment variable set. For example:
$ unzip apache-ant-1.7.0.zip $ export ANT_HOME=~/apache-ant-1.7.0
Then, you can install the update. The update script will use Maven to download the Web Beans and EJB3 automatically.
$ cd webbeans-1.0.0.ALPHA1/jboss-as $ ant update
Now, you're ready to deploy your first example!
The build scripts for the examples offer a number of targets, these are:
ant restart
- deploy the example in exploded format
ant explode
- update an exploded example, without restarting the deployment
ant deploy
- deploy the example in compressed jar format
ant undeploy
- remove the example from the server
ant clean
- clean the example
To deploy the numberguess example:
$ cd examples/numberguess ant deploy
Wait for the application to deploy, and enjoy hours of fun at http://localhost:8080/webbeans-numberguess!
The Web Beans RI includes a second simple example that will translate your text into Latin. The numberguess example is a war example, and uses only simple beans; the translator example is an ear example, and includes enterprise beans, packaged in an EJB module. To try it out:
$ cd examples/translator ant deploy
Wait for the application to deploy, and visit http://localhost:8080/webbeans-translator!
In the numberguess application you get given 10 attempts to guess a number between 1 and 100. After each attempt, you will be told whether you are too high, or too low.
The numberguess example is comprised of a number of Web Beans, configuration files, and Facelet JSF pages, packaged as a war. Let's start with the configuration files.
All the configuration files for this example are located in WEB-INF/
, which is stored in WebContent
in the source tree. First, we have faces-config.xml
, in which we tell JSF to use Facelets:
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="1.2"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
<application>
<view-handler
>com.sun.facelets.FaceletViewHandler</view-handler>
</application>
</faces-config
>
There is an empty web-beans.xml
file, which marks this application as a Web Beans application.
Finally there is web.xml
:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name >Web Beans Numbergues example</display-name> <!-- JSF --><servlet> <servlet-name >Faces Servlet</servlet-name> <servlet-class >javax.faces.webapp.FacesServlet</servlet-class> <load-on
-startup >1</load-on-startup> </servlet> <servlet-mapping> <servlet
-name >Faces Servlet</servlet-name> <url-pattern >*.jsf</url-pattern> </servlet-mapping>
<context-param> <param-name >javax.faces.DEFAULT_SUFFIX</param-name> <param-v
alue >.xhtml</param-value> </context-param> <session-config> <session-timeout >10</session-timeout> </session-config> <listener> <listener-class >org.jboss.webbeans.servlet.WebBeansListener</listener-class> </listener> </web-app >
![]() | Enable and load the JSF servlet |
![]() | Configure requests to |
![]() | Tell JSF that we will be giving our source files (facelets) an extension of |
![]() | Configure a session timeout of 10 minutes |
![]() | Configure the Web Beans listener, so that Web Beans services can be used in the servlet request |
The only configuration required by the Web Beans RI in web.xml
is to add the Web Beans listener.
Whilst this demo is a JSF demo, you can use the Web Beans RI with any Servlet based web framework; just configure the Web Beans listener.
Let's take a look at the Facelet view:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:s="http://jboss.com/products/seam/taglib"> <ui:composition template="template.xhtml"> <ui:define name="content"> <h1 >Guess a number...</h1> <h:form
id="NumberGuessMain"> <div style="color: red"> <h:messages id="messages" globalOnly="false"/> <h:outputText id="Higher" value="Higher!" rendered="#{game.number gt game.guess}"/> <h:outputText id="Lower" value="Lower!" rendered="#{game.number lt game.guess}"/> </div> <div
> I'm thinking of a number between #{game.smallest} and #{game.biggest}. You have #{game.remainingGuesses} guesses. </div> <div> Y
our guess: <h:inputText id="inputGuess" value="#{game.guess}" required="true"
size="3"> <f:validateLongRange maximum="#{game.biggest}" minimum="#{game.smallest}"/> <
/h:inputText> <h:commandButton id="GuessButton" value="Guess" action="#{game.check}"/> </div> </h:form> </ui:define> </ui:composition> </html >
![]() | Facelets is a templating language for JSF, here we are wrapping our page in a template which defines the header. |
![]() | There are a number of messages which can be sent to the user, "Higher!", "Lower!" and "Correct!" |
![]() | As the user guesses, the range of numbers they can guess gets smaller - this sentance changes to make sure they know what range to guess in. |
![]() | This input field is bound to a Web Bean, using the value expression. |
![]() | A range validator is used to make sure the user doesn't accidentally input a number outside of the range in which they can guess - if the validator wasn't here, the user might use up a guess on an out of range number. |
![]() | And, of course, there must be a way for the user to send their guess to the server. Here we bind to an action method on the Web Bean. |
The example exists of 4 classes, the first two of which are binding types. First, there is the @Random
binding type, used for injecting a random number:
@Target( { TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
@BindingType
public @interface Random {}
There is also the @MaxNumber
binding type, used for injecting the maximum number that can be injected:
@Target( { TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
@BindingType
public @interface MaxNumber {}
The Generator
class is responsible for creating the random number, via a producer method. It also exposes the maximum possible number via a producer method:
@ApplicationScoped
public class Generator {
private java.util.Random random = new java.util.Random( System.currentTimeMillis() );
private int maxNumber = 100;
java.util.Random getRandom()
{
return random;
}
@Produces @Random int next() {
return getRandom().nextInt(maxNumber);
}
@Produces @MaxNumber int getMaxNumber()
{
return maxNumber;
}
}
You'll notice that the Generator
is application scoped; therefore we don't get a different random each time.
The final Web Bean in the application is the session scoped Game
. By making Game
session scoped, you can only play the game once per browser session. You could easily add a reset button - a good exercise for the reader :-)
You'll also note that we've used the @Named
annotation, so that we can use the bean through EL in the JSF page. Finally, we've used constructor injection to initialize the game with a random number. And of course, we need to tell the player when they've won, so we give feedback with a FacesMessage
.
@Named
@SessionScoped
public class Game {
private int number;
private int guess;
private int smallest;
private int biggest;
private int remainingGuesses;
public Game() {}
@Initializer
Game(@Random int number, @MaxNumber int maxNumber) {
this.number = number;
this.smallest = 1;
this.biggest = maxNumber;
this.remainingGuesses = 10;
}
// Getters and setters for fields
public String check() {
if (guess
>number) {
biggest = guess - 1;
}
if (guess<number) {
smallest = guess + 1;
}
if (guess == number) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Correct!"));
}
remainingGuesses--;
return null;
}
}
L'esempio del traduttore prende le frasi che vengono inserite e le traduce in latino.
The translator example is built as an ear, and contains EJBs and enterprise beans. As a result, it's structure is more complex than the numberguess example.
EJB 3.1 and Jave EE 6 allow you to package EJBs in a war, which will make this structure much simpler!
First, let's take a look at the ear aggregator, which is located in webbeans-translator-ear
module. Maven automatically generates the application.xml
and jboss-app.xml
for us:
<plugin>
<groupId
>org.apache.maven.plugins</groupId>
<artifactId
>maven-ear-plugin</artifactId>
<configuration>
<modules>
<webModule>
<groupId
>org.jboss.webbeans.examples.translator</groupId>
<artifactId
>webbeans-translator-war</artifactId>
<contextRoot
>/webbeans-translator</contextRoot>
</webModule>
</modules>
<jboss>
<loader-repository
>webbeans.jboss.org:loader=webbeans-translator</loader-repository>
</jboss>
</configuration>
</plugin
>
We're doing a couple of things here - firstly we set the context path, which gives us a nice url (http://localhost:8080/webbeans-translator) and we also enable class loader isolation for JBoss AS.
If you aren't using Maven to generate these files, you would need META-INF/jboss-app.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jboss-app
PUBLIC "-//JBoss//DTD J2EE Application 4.2//EN"
"http://www.jboss.org/j2ee/dtd/jboss-app_4_2.dtd">
<jboss-app>
<loader-repository
>webbeans.jboss.org:loader=webbeans-translator</loader-repository>
</jboss-app
>
e META-INF/application.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd"
version="5">
<display-name
>webbeans-translator-ear</display-name>
<description
>Ear Example for the reference implementation of JSR 299: Web Beans</description>
<module>
<web>
<web-uri
>webbeans-translator.war</web-uri>
<context-root
>/webbeans-translator</context-root>
</web>
</module>
<module>
<ejb
>webbeans-translator.jar</ejb>
</module>
</application
>
Next, lets look at the war. Just as in the numberguess example, we have a faces-config.xml
(to enabled Facelets) and a web.xml
(to enable JSF and attach Web Beans services to the servlet container) in WebContent/WEB-INF
.
More intersting is the facelet used to translate text. Just as in the numberguess example we have a template, which surrounds the form (ommitted here for brevity):
<h:form id="NumberGuessMain">
<table>
<tr align="center" style="font-weight: bold" >
<td>
Your text
</td>
<td>
Translation
</td>
</tr>
<tr>
<td>
<h:inputTextarea id="text" value="#{translator.text}" required="true" rows="5" cols="80" />
</td>
<td>
<h:outputText value="#{translator.translatedText}" />
</td>
</tr>
</table>
<div>
<h:commandButton id="button" value="Translate" action="#{translator.translate}"/>
</div>
</h:form
>
The user can enter some text in the lefthand textarea, and hit the translate button to see the result to the right.
Finally, let's look at the ejb module, webbeans-translator-ejb
. There are two configuration files in src/main/resources/META-INF
, an empty web-beans.xml
, used to mark the archive as containing Web Beans, and ejb-jar.xml
. Web Beans provides injection and initializtion services for all EJBs, and uses ejb-jar.xml
to enable this, you'll need this in any EJB project which uses Web Beans:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"
version="3.0">
<interceptors>
<interceptor>
<interceptor-class
>org.jboss.webbeans.ejb.SessionBeanInterceptor</interceptor-class>
</interceptor>
</interceptors>
<assembly-descriptor>
<interceptor-binding>
<ejb-name
>*</ejb-name>
<interceptor-class
>org.jboss.webbeans.ejb.SessionBeanInterceptor</interceptor-class>
</interceptor-binding>
</assembly-descriptor>
</ejb-jar
>
We've saved the most interesting bit to last, the code! The project has two simple beans, SentanceParser
and TextTranslator
and two enterprise beans, TanslatorControllerBean
and SentenceTranslator
. You should be getting quite familiar with what a Web Bean looks like by now, so we'll just highlight the most interesting bits here.
Both SentanceParser
and TextTranslator
are dependent beans, and TextTranslator
uses constructor initialization:
public class TextTranslator {
private SentenceParser sentenceParser;
private Translator sentenceTranslator;
@Initializer
TextTranslator(SentenceParser sentenceParser, Translator sentenceTranslator)
{
this.sentenceParser = sentenceParser;
this.sentenceTranslator = sentenceTranslator;
TextTranslator
is a stateless bean (with a local business interface), where the magic happens - of course, we couldn't develop a full translator, but we gave it a good go!
Finally, there is UI orientated controller, that collects the text from the user, and dispatches it to the translator. This is a request scoped, named, stateful session bean, which injects the translator.
@Stateful
@RequestScoped
@Named("translator")
public class TranslatorControllerBean implements TranslatorController
{
@Current TextTranslator translator;
The bean also has getters and setters for all the fields on the page.
As this is a stateful session bean, we have to have a remove method:
@Remove
public void remove()
{
}
The Web Beans manager will call the remove method for you when the bean is destroyed; in this case at the end of the request.
That concludes our short tour of the Web Beans RI examples. For more on the RI, or to help out, please visit http://www.seamframework.org/WebBeans/Development.
We need help in all areas - bug fixing, writing new features, writing examples and translating this reference guide.
Web Beans supports three primary mechanisms for dependency injection:
Constructor parameter injection:
public class Checkout {
private final ShoppingCart cart;
@Initializer
public Checkout(ShoppingCart cart) {
this.cart = cart;
}
}
Initializer method parameter injection:
public class Checkout {
private ShoppingCart cart;
@Initializer
void setShoppingCart(ShoppingCart cart) {
this.cart = cart;
}
}
And direct field injection:
public class Checkout {
private @Current ShoppingCart cart;
}
Dependency injection always occurs when the Web Bean instance is first instantiated.
First, the Web Bean manager calls the Web Bean constructor, to obtain an instance of the Web Bean.
Next, the Web Bean manager initializes the values of all injected fields of the Web Bean.
Next, the Web Bean manager calls all initializer methods of Web Bean.
Finally, the @PostConstruct
method of the Web Bean, if any, is called.
Constructor parameter injection is not supported for EJB beans, since the EJB is instantiated by the EJB container, not the Web Bean manager.
Parameters of constructors and initializer methods need not be explicitly annotated when the default binding type @Current
applies. Injected fields, however, must specify a binding type, even when the default binding type applies. If the field does not specify a binding type, it will not be injected.
Producer methods also support parameter injection:
@Produces Checkout createCheckout(ShoppingCart cart) {
return new Checkout(cart);
}
Finally, observer methods (which we'll meet in Capitolo 9, Eventi), disposal methods and destructor methods all support parameter injection.
The Web Beans specification defines a procedure, called the typesafe resolution algorithm, that the Web Bean manager follows when identifying the Web Bean to inject to an injection point. This algorithm looks complex at first, but once you understand it, it's really quite intuitive. Typesafe resolution is performed at system initialization time, which means that the manager will inform the user immediately if a Web Bean's dependencies cannot be satisfied, by throwing a UnsatisfiedDependencyException
or AmbiguousDependencyException
.
The purpose of this algorithm is to allow multiple Web Beans to implement the same API type and either:
allow the client to select which implementation it requires using binding annotations,
allow the application deployer to select which implementation is appropriate for a particular deployment, without changes to the client, by enabling or disabling deployment types, or
allow one implementation of an API to override another implementation of the same API at deployment time, without changes to the client, using deployment type precedence.
Let's explore how the Web Beans manager determines a Web Bean to be injected.
If we have more than one Web Bean that implements a particular API type, the injection point can specify exactly which Web Bean should be injected using a binding annotation. For example, there might be two implementations of PaymentProcessor
:
@PayByCheque
public class ChequePaymentProcessor implements PaymentProcessor {
public void process(Payment payment) { ... }
}
@PayByCreditCard
public class CreditCardPaymentProcessor implements PaymentProcessor {
public void process(Payment payment) { ... }
}
Where @PayByCheque
and @PayByCreditCard
are binding annotations:
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
@BindingType
public @interface PayByCheque {}
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
@BindingType
public @interface PayByCreditCard {}
A client Web Bean developer uses the binding annotation to specify exactly which Web Bean should be injected.
Using field injection:
@PayByCheque PaymentProcessor chequePaymentProcessor;
@PayByCreditCard PaymentProcessor creditCardPaymentProcessor;
Using initializer method injection:
@Initializer
public void setPaymentProcessors(@PayByCheque PaymentProcessor chequePaymentProcessor,
@PayByCreditCard PaymentProcessor creditCardPaymentProcessor) {
this.chequePaymentProcessor = chequePaymentProcessor;
this.creditCardPaymentProcessor = creditCardPaymentProcessor;
}
Or using constructor injection:
@Initializer
public Checkout(@PayByCheque PaymentProcessor chequePaymentProcessor,
@PayByCreditCard PaymentProcessor creditCardPaymentProcessor) {
this.chequePaymentProcessor = chequePaymentProcessor;
this.creditCardPaymentProcessor = creditCardPaymentProcessor;
}
Binding annotations may have members:
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
@BindingType
public @interface PayBy {
PaymentType value();
}
In which case, the member value is significant:
@PayBy(CHEQUE) PaymentProcessor chequePaymentProcessor;
@PayBy(CREDIT_CARD) PaymentProcessor creditCardPaymentProcessor;
You can tell the Web Bean manager to ignore a member of a binding annotation type by annotating the member @NonBinding
.
An injection point may even specify multiple binding annotations:
@Asynchronous @PayByCheque PaymentProcessor paymentProcessor
In this case, only a Web Bean which has both binding annotations would be eligible for injection.
Even producer methods may specify binding annotations:
@Retention(RUNTIME)
@Target({TYPE, METHOD})
@DeploymentType
public @interface Mock {}
Web Beans defines a binding type @Current
that is the default binding type for any injection point or Web Bean that does not explicitly specify a binding type.
There are two common circumstances in which it is necessary to explicitly specify @Current
:
on a field, in order to declare it as an injected field with the default binding type, and
on a Web Bean which has another binding type in addition to the default binding type.
All Web Beans have a deployment type. Each deployment type identifies a set of Web Beans that should be conditionally installed in some deployments of the system.
For example, we could define a deployment type named @Mock
, which would identify Web Beans that should only be installed when the system executes inside an integration testing environment:
@Retention(RUNTIME)
@Target({TYPE, METHOD})
@DeploymentType
public @interface Mock {}
Suppose we had some Web Bean that interacted with an external system to process payments:
public class ExternalPaymentProcessor {
public void process(Payment p) {
...
}
}
Since this Web Bean does not explicitly specify a deployment type, it has the default deployment type @Production
.
For integration or unit testing, the external system is slow or unavailable. So we would create a mock object:
@Mock
public class MockPaymentProcessor implements PaymentProcessor {
@Override
public void process(Payment p) {
p.setSuccessful(true);
}
}
But how does the Web Bean manager determine which implementation to use in a particular deployment?
Web Beans defines two built-in deployment types: @Production
and @Standard
. By default, only Web Beans with the built-in deployment types are enabled when the system is deployed. We can identify additional deployment types to be enabled in a particular deployment by listing them in web-beans.xml
.
Going back to our example, when we deploy our integration tests, we want all our @Mock
objects to be installed:
<WebBeans>
<Deploy>
<Standard/>
<Production/>
<test:Mock/>
</Deploy>
</WebBeans
>
Now the Web Bean manager will identify and install all Web Beans annotated @Production
, @Standard
or @Mock
at deployment time.
The deployment type @Standard
is used only for certain special Web Beans defined by the Web Beans specification. We can't use it for our own Web Beans, and we can't disable it.
The deployment type @Production
is the default deployment type for Web Beans which don't explicitly declare a deployment type, and may be disabled.
If you've been paying attention, you're probably wondering how the Web Bean manager decides which implementationExternalPaymentProcessor
or MockPaymentProcessor
to choose. Consider what happens when the manager encounters this injection point:
@Current PaymentProcessor paymentProcessor
There are now two Web Beans which satisfy the PaymentProcessor
contract. Of course, we can't use a binding annotation to disambiguate, since binding annotations are hard-coded into the source at the injection point, and we want the manager to be able to decide at deployment time!
The solution to this problem is that each deployment type has a different precedence. The precedence of the deployment types is determined by the order in which they appear in web-beans.xml
. In our example, @Mock
appears later than @Production
so it has a higher precedence.
Whenever the manager discovers that more than one Web Bean could satisfy the contract (API type plus binding annotations) specified by an injection point, it considers the relative precedence of the Web Beans. If one has a higher precedence than the others, it chooses the higher precedence Web Bean to inject. So, in our example, the Web Bean manager will inject MockPaymentProcessor
when executing in our integration testing environment (which is exactly what we want).
It's interesting to compare this facility to today's popular manager architectures. Various "lightweight" containers also allow conditional deployment of classes that exist in the classpath, but the classes that are to be deployed must be explicity, individually, listed in configuration code or in some XML configuration file. Web Beans does support Web Bean definition and configuration via XML, but in the common case where no complex configuration is required, deployment types allow a whole set of Web Beans to be enabled with a single line of XML. Meanwhile, a developer browsing the code can easily identify what deployment scenarios the Web Bean will be used in.
Deployment types are useful for all kinds of things, here's some examples:
@Mock
and @Staging
deployment types for testing
@AustralianTaxLaw
for site-specific Web Beans
@SeamFramework
, @Guice
for third-party frameworks which build on Web Beans
@Standard
for standard Web Beans defined by the Web Beans specification
I'm sure you can think of more applications...
The typesafe resolution algorithm fails when, after considering the binding annotations and and deployment types of all Web Beans that implement the API type of an injection point, the Web Bean manager is unable to identify exactly one Web Bean to inject.
It's usually easy to fix an UnsatisfiedDependencyException
or AmbiguousDependencyException
.
To fix an UnsatisfiedDependencyException
, simply provide a Web Bean which implements the API type and has the binding types of the injection pointor enable the deployment type of a Web Bean that already implements the API type and has the binding types.
To fix an AmbiguousDependencyException
, introduce a binding type to distinguish between the two implementations of the API type, or change the deployment type of one of the implementations so that the Web Bean manager can use deployment type precedence to choose between them. An AmbiguousDependencyException
can only occur if two Web Beans share a binding type and have exactly the same deployment type.
There's one more issue you need to be aware of when using dependency injection in Web Beans.
Clients of an injected Web Bean do not usually hold a direct reference to a Web Bean instance.
Imagine that a Web Bean bound to the application scope held a direct reference to a Web Bean bound to the request scope. The application scoped Web Bean is shared between many different requests. However, each request should see a different instance of the request scoped Web bean!
Now imagine that a Web Bean bound to the session scope held a direct reference to a Web Bean bound to the application scope. From time to time, the session context is serialized to disk in order to use memory more efficiently. However, the application scoped Web Bean instance should not be serialized along with the session scoped Web Bean!
Therefore, unless a Web Bean has the default scope @Dependent
, the Web Bean manager must indirect all injected references to the Web Bean through a proxy object. This client proxy is responsible for ensuring that the Web Bean instance that receives a method invocation is the instance that is associated with the current context. The client proxy also allows Web Beans bound to contexts such as the session context to be serialized to disk without recursively serializing other injected Web Beans.
Unfortunately, due to limitations of the Java language, some Java types cannot be proxied by the Web Bean manager. Therefore, the Web Bean manager throws an UnproxyableDependencyException
if the type of an injection point cannot be proxied.
The following Java types cannot be proxied by the Web Bean manager:
classes which are declared final
or have a final
method,
classes which have no non-private constructor with no parameters, and
arrays and primitive types.
It's usually very easy to fix an UnproxyableDependencyException
. Simply add a constructor with no parameters to the injected class, introduce an interface, or change the scope of the injected Web Bean to @Dependent
.
The application may obtain an instance of the interface Manager
by injection:
@Current Manager manager;
The Manager
object provides a set of methods for obtaining a Web Bean instance programatically.
PaymentProcessor p = manager.getInstanceByType(PaymentProcessor.class);
Binding annotations may be specified by subclassing the helper class AnnotationLiteral
, since it is otherwise difficult to instantiate an annotation type in Java.
PaymentProcessor p = manager.getInstanceByType(PaymentProcessor.class,
new AnnotationLiteral<CreditCard
>(){});
If the binding type has an annotation member, we can't use an anonymous subclass of AnnotationLiteral
instead we'll need to create a named subclass:
abstract class CreditCardBinding
extends AnnotationLiteral<CreditCard
>
implements CreditCard {}
PaymentProcessor p = manager.getInstanceByType(PaymentProcessor.class,
new CreditCardBinding() {
public void value() { return paymentType; }
} );
Enterprise Web Beans support all the lifecycle callbacks defined by the EJB specification: @PostConstruct
, @PreDestroy
, @PrePassivate
and @PostActivate
.
Simple Web Beans support only the @PostConstruct
and @PreDestroy
callbacks.
Both enterprise and simple Web Beans support the use of @Resource
, @EJB
and @PersistenceContext
for injection of Java EE resources, EJBs and JPA persistence contexts, respectively. Simple Web Beans do not support the use of @PersistenceContext(type=EXTENDED)
.
The @PostConstruct
callback always occurs after all dependencies have been injected.
There are certain kinds of dependent objectsWeb Beans with scope @Dependent
that need to know something about the object or injection point into which they are injected in order to be able to do what they do. For example:
The log category for a Logger
depends upon the class of the object that owns it.
Injection of a HTTP parameter or header value depends upon what parameter or header name was specified at the injection point.
Injection of the result of an EL expression evaluation depends upon the expression that was specified at the injection point.
A Web Bean with scope @Dependent
may inject an instance of InjectionPoint
and access metadata relating to the injection point to which it belongs.
Let's look at an example. The following code is verbose, and vulnerable to refactoring problems:
Logger log = Logger.getLogger(MyClass.class.getName());
This clever little producer method lets you inject a JDK Logger
without explicitly specifying the log category:
class LogFactory {
@Produces Logger createLogger(InjectionPoint injectionPoint) {
return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
}
}
We can now write:
@Current Logger log;
Not convinced? Then here's a second example. To inject HTTP parameters, we need to define a binding type:
@BindingType
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface HttpParam {
@NonBinding public String value();
}
We would use this binding type at injection points as follows:
@HttpParam("username") String username;
@HttpParam("password") String password;
The following producer method does the work:
class HttpParams
@Produces @HttpParam("")
String getParamValue(ServletRequest request, InjectionPoint ip) {
return request.getParameter(ip.getAnnotation(HttpParam.class).value());
}
}
(Note that the value()
member of the HttpParam
annotation is ignored by the Web Bean manager since it is annotated @NonBinding.
)
The Web Bean manager provides a built-in Web Bean that implements the InjectionPoint
interface:
public interface InjectionPoint {
public Object getInstance();
public Bean<?> getBean();
public Member getMember():
public <T extends Annotation
> T getAnnotation(Class<T
> annotation);
public Set<T extends Annotation
> getAnnotations();
}
So far, we've seen a few examples of scope type annotations. The scope of a Web Bean determines the lifecycle of instances of the Web Bean. The scope also determines which clients refer to which instances of the Web Bean. According to the Web Beans specification, a scope determines:
When a new instance of any Web Bean with that scope is created
When an existing instance of any Web Bean with that scope is destroyed
Which injected references refer to any instance of a Web Bean with that scope
For example, if we have a session scoped Web Bean, CurrentUser
, all Web Beans that are called in the context of the same HttpSession
will see the same instance of CurrentUser
. This instance will be automatically created the first time a CurrentUser
is needed in that session, and automatically destroyed when the session ends.
Web Beans features an extensible context model. It is possible to define new scopes by creating a new scope type annotation:
@Retention(RUNTIME)
@Target({TYPE, METHOD})
@ScopeType
public @interface ClusterScoped {}
Of course, that's the easy part of the job. For this scope type to be useful, we will also need to define a Context
object that implements the scope! Implementing a Context
is usually a very technical task, intended for framework development only.
We can apply a scope type annotation to a Web Bean implementation class to specify the scope of the Web Bean:
@ClusterScoped
public class SecondLevelCache { ... }
Usually, you'll use one of Web Beans' built-in scopes.
Web Beans defines four built-in scopes:
@RequestScoped
@SessionScoped
@ApplicationScoped
@ConversationScoped
For a web application that uses Web Beans:
any servlet request has access to active request, session and application scopes, and, additionally
any JSF request has access to an active conversation scope.
The request and application scopes are also active:
during invocations of EJB remote methods,
during EJB timeouts,
during message delivery to a message-driven bean, and
during web service invocations.
If the application tries to invoke a Web Bean with a scope that does not have an active context, a ContextNotActiveException
is thrown by the Web Bean manager at runtime.
Three of the four built-in scopes should be extremely familiar to every Java EE developer, so let's not waste time discussing them here. One of the scopes, however, is new.
The Web Beans conversation scope is a bit like the traditional session scope in that it holds state associated with a user of the system, and spans multiple requests to the server. However, unlike the session scope, the conversation scope:
is demarcated explicitly by the application, and
holds state associated with a particular web browser tab in a JSF application.
A conversation represents a task, a unit of work from the point of view of the user. The conversation context holds state associated with what the user is currently working on. If the user is doing multiple things at the same time, there are multiple conversations.
The conversation context is active during any JSF request. However, most conversations are destroyed at the end of the request. If a conversation should hold state across multiple requests, it must be explicitly promoted to a long-running conversation.
Web Beans provides a built-in Web Bean for controlling the lifecyle of conversations in a JSF application. This Web Bean may be obtained by injection:
@Current Conversation conversation;
To promote the conversation associated with the current request to a long-running conversation, call the begin()
method from application code. To schedule the current long-running conversation context for destruction at the end of the current request, call end()
.
In the following example, a conversation-scoped Web Bean controls the conversation with which it is associated:
@ConversationScoped @Stateful
public class OrderBuilder {
private Order order;
private @Current Conversation conversation;
private @PersistenceContext(type=EXTENDED) EntityManager em;
@Produces public Order getOrder() {
return order;
}
public Order createOrder() {
order = new Order();
conversation.begin();
return order;
}
public void addLineItem(Product product, int quantity) {
order.add( new LineItem(product, quantity) );
}
public void saveOrder(Order order) {
em.persist(order);
conversation.end();
}
@Remove
public void destroy() {}
}
This Web Bean is able to control its own lifecycle through use of the Conversation
API. But some other Web Beans have a lifecycle which depends completely upon another object.
The conversation context automatically propagates with any JSF faces request (JSF form submission). It does not automatically propagate with non-faces requests, for example, navigation via a link.
We can force the conversation to propagate with a non-faces request by including the unique identifier of the conversation as a request parameter. The Web Beans specification reserves the request parameter named cid
for this use. The unique identifier of the conversation may be obtained from the Conversation
object, which has the Web Beans name conversation
.
Therefore, the following link propagates the conversation:
<a href="/addProduct.jsp?cid=#{conversation.id}" >Add Product</a >
The Web Bean manager is also required to propagate conversations across any redirect, even if the conversation is not marked long-running. This makes it very easy to implement the common POST-then-redirect pattern, without resort to fragile constructs such as a "flash" object. In this case, the Web Bean manager automatically adds a request parameter to the redirect URL.
The Web Bean manager is permitted to destroy a conversation and all state held in its context at any time in order to preserve resources. A Web Bean manager implementation will normally do this on the basis of some kind of timeoutthough this is not required by the Web Beans specification. The timeout is the period of inactivity before the conversation is destroyed.
The Conversation
object provides a method to set the timeout. This is a hint to the Web Bean manager, which is free to ignore the setting.
conversation.setTimeout(timeoutInMillis);
In addition to the four built-in scopes, Web Beans features the so-called dependent pseudo-scope. This is the default scope for a Web Bean which does not explicitly declare a scope type.
For example, this Web Bean has the scope type @Dependent
:
public class Calculator { ... }
When an injection point of a Web Bean resolves to a dependent Web Bean, a new instance of the dependent Web Bean is created every time the first Web Bean is instantiated. Instances of dependent Web Beans are never shared between different Web Beans or different injection points. They are dependent objects of some other Web Bean instance.
Dependent Web Bean instances are destroyed when the instance they depend upon is destroyed.
Web Beans makes it easy to obtain a dependent instance of a Java class or EJB bean, even if the class or EJB bean is already declared as a Web Bean with some other scope type.
The built-in @New
binding annotation allows implicit definition of a dependent Web Bean at an injection point. Suppose we declare the following injected field:
@New Calculator calculator;
Then a Web Bean with scope @Dependent
, binding type @New
, API type Calculator
, implementation class Calculator
and deployment type @Standard
is implicitly defined.
This is true even if Calculator
is already declared with a different scope type, for example:
@ConversationScoped
public class Calculator { ... }
So the following injected attributes each get a different instance of Calculator
:
public class PaymentCalc {
@Current Calculator calculator;
@New Calculator newCalculator;
}
The calculator
field has a conversation-scoped instance of Calculator
injected. The newCalculator
field has a new instance of Calculator
injected, with a lifecycle that is bound to the owning PaymentCalc
.
This feature is particularly useful with producer methods, as we'll see in the next chapter.
Producer methods let us overcome certain limitations that arise when the Web Bean manager, instead of the application, is responsible for instantiating objects. They're also the easiest way to integrate objects which are not Web Beans into the Web Beans environment. (We'll meet a second approach in Capitolo 12, Definire i Web Beans tramite XML.)
Secondo la specifica:
A Web Beans producer method acts as a source of objects to be injected, where:
the objects to be injected are not required to be instances of Web Beans,
the concrete type of the objects to be injected may vary at runtime or
the objects require some custom initialization that is not performed by the Web Bean constructor
For example, producer methods let us:
expose a JPA entity as a Web Bean,
expose any JDK class as a Web Bean,
define multiple Web Beans, with different scopes or initialization, for the same implementation class, or
vary the implementation of an API type at runtime.
In particular, producer methods let us use runtime polymorphism with Web Beans. As we've seen, deployment types are a powerful solution to the problem of deployment-time polymorphism. But once the system is deployed, the Web Bean implementation is fixed. A producer method has no such limitation:
@SessionScoped
public class Preferences {
private PaymentStrategyType paymentStrategy;
...
@Produces @Preferred
public PaymentStrategy getPaymentStrategy() {
switch (paymentStrategy) {
case CREDIT_CARD: return new CreditCardPaymentStrategy();
case CHEQUE: return new ChequePaymentStrategy();
case PAYPAL: return new PayPalPaymentStrategy();
default: return null;
}
}
}
Consider an injection point:
@Preferred PaymentStrategy paymentStrat;
This injection point has the same type and binding annotations as the producer method, so it resolves to the producer method using the usual Web Beans injection rules. The producer method will be called by the Web Bean manager to obtain an instance to service this injection point.
.The scope of the producer method defaults to @Dependent
, and so it will be called every time the Web Bean manager injects this field or any other field that resolves to the same producer method. Thus, there could be multiple instances of the PaymentStrategy
object for each user session.
To change this behavior, we can add a @SessionScoped
annotation to the method.
@Produces @Preferred @SessionScoped
public PaymentStrategy getPaymentStrategy() {
...
}
Now, when the producer method is called, the returned PaymentStrategy
will be bound to the session context. The producer method won't be called again in the same session.
There's one potential problem with the code above. The implementations of CreditCardPaymentStrategy
are instantiated using the Java new
operator. Objects instantiated directly by the application can't take advantage of dependency injection and don't have interceptors.
If this isn't what we want we can use dependency injection into the producer method to obtain Web Bean instances:
@Produces @Preferred @SessionScoped
public PaymentStrategy getPaymentStrategy(CreditCardPaymentStrategy ccps,
ChequePaymentStrategy cps,
PayPalPaymentStrategy ppps) {
switch (paymentStrategy) {
case CREDIT_CARD: return ccps;
case CHEQUE: return cps;
case PAYPAL: return ppps;
default: return null;
}
}
Wait, what if CreditCardPaymentStrategy
is a request scoped Web Bean? Then the producer method has the effect of "promoting" the current request scoped instance into session scope. This is almost certainly a bug! The request scoped object will be destroyed by the Web Bean manager before the session ends, but the reference to the object will be left "hanging" in the session scope. This error will not be detected by the Web Bean manager, so please take extra care when returning Web Bean instances from producer methods!
There's at least three ways we could go about fixing this bug. We could change the scope of the CreditCardPaymentStrategy
implementation, but this would affect other clients of that Web Bean. A better option would be to change the scope of the producer method to @Dependent
or @RequestScoped
.
But a more common solution is to use the special @New
binding annotation.
Consider the following producer method:
@Produces @Preferred @SessionScoped
public PaymentStrategy getPaymentStrategy(@New CreditCardPaymentStrategy ccps,
@New ChequePaymentStrategy cps,
@New PayPalPaymentStrategy ppps) {
switch (paymentStrategy) {
case CREDIT_CARD: return ccps;
case CHEQUE: return cps;
case PAYPAL: return ppps;
default: return null;
}
}
Then a new dependent instance of CreditCardPaymentStrategy
will be created, passed to the producer method, returned by the producer method and finally bound to the session context. The dependent object won't be destroyed until the Preferences
object is destroyed, at the end of the session.
The first major theme of Web Beans is loose coupling. We've already seen three means of achieving loose coupling:
deployment types enable deployment time polymorphism,
producer methods enable runtime polymorphism, and
contextual lifecycle management decouples Web Bean lifecycles.
These techniques serve to enable loose coupling of client and server. The client is no longer tightly bound to an implementation of an API, nor is it required to manage the lifecycle of the server object. This approach lets stateful objects interact as if they were services.
Loose coupling makes a system more dynamic. The system can respond to change in a well-defined manner. In the past, frameworks that attempted to provide the facilities listed above invariably did it by sacrificing type safety. Web Beans is the first technology that achieves this level of loose coupling in a typesafe way.
Web Beans provides three extra important facilities that further the goal of loose coupling:
interceptors decouple technical concerns from business logic,
decorators may be used to decouple some business concerns, and
event notifications decouple event producers from event consumers.
Let's explore interceptors first.
Web Beans re-uses the basic interceptor architecture of EJB 3.0, extending the functionality in two directions:
Any Web Bean may have interceptors, not just session beans.
Web Beans features a more sophisticated annotation-based approach to binding interceptors to Web Beans.
The EJB specification defines two kinds of interception points:
business method interception, and
lifecycle callback interception.
A business method interceptor applies to invocations of methods of the Web Bean by clients of the Web Bean:
public class TransactionInterceptor {
@AroundInvoke public Object manageTransaction(InvocationContext ctx) { ... }
}
A lifecycle callback interceptor applies to invocations of lifecycle callbacks by the container:
public class DependencyInjectionInterceptor {
@PostConstruct public void injectDependencies(InvocationContext ctx) { ... }
}
An interceptor class may intercept both lifecycle callbacks and business methods.
Suppose we want to declare that some of our Web Beans are transactional. The first thing we need is an interceptor binding annotation to specify exactly which Web Beans we're interested in:
@InterceptorBindingType
@Target({METHOD, TYPE})
@Retention(RUNTIME)
public @interface Transactional {}
Now we can easily specify that our ShoppingCart
is a transactional object:
@Transactional
public class ShoppingCart { ... }
Or, if we prefer, we can specify that just one method is transactional:
public class ShoppingCart {
@Transactional public void checkout() { ... }
}
That's great, but somewhere along the line we're going to have to actually implement the interceptor that provides this transaction management aspect. All we need to do is create a standard EJB interceptor, and annotate it @Interceptor
and @Transactional
.
@Transactional @Interceptor
public class TransactionInterceptor {
@AroundInvoke public Object manageTransaction(InvocationContext ctx) { ... }
}
All Web Beans interceptors are simple Web Beans, and can take advantage of dependency injection and contextual lifecycle management.
@ApplicationScoped @Transactional @Interceptor
public class TransactionInterceptor {
@Resource Transaction transaction;
@AroundInvoke public Object manageTransaction(InvocationContext ctx) { ... }
}
Multiple interceptors may use the same interceptor binding type.
Finally, we need to enable our interceptor in web-beans.xml
.
<Interceptors>
<tx:TransactionInterceptor/>
</Interceptors
>
Whoah! Why the angle bracket stew?
Well, the XML declaration solves two problems:
it enables us to specify a total ordering for all the interceptors in our system, ensuring deterministic behavior, and
it lets us enable or disable interceptor classes at deployment time.
For example, we could specify that our security interceptor runs before our TransactionInterceptor
.
<Interceptors>
<sx:SecurityInterceptor/>
<tx:TransactionInterceptor/>
</Interceptors
>
Or we could turn them both off in our test environment!
Suppose we want to add some extra information to our @Transactional
annotation:
@InterceptorBindingType
@Target({METHOD, TYPE})
@Retention(RUNTIME)
public @interface Transactional {
boolean requiresNew() default false;
}
Web Beans will use the value of requiresNew
to choose between two different interceptors, TransactionInterceptor
and RequiresNewTransactionInterceptor
.
@Transactional(requiresNew=true) @Interceptor
public class RequiresNewTransactionInterceptor {
@AroundInvoke public Object manageTransaction(InvocationContext ctx) { ... }
}
Now we can use RequiresNewTransactionInterceptor
like this:
@Transactional(requiresNew=true)
public class ShoppingCart { ... }
But what if we only have one interceptor and we want the manager to ignore the value of requiresNew
when binding interceptors? We can use the @NonBinding
annotation:
@InterceptorBindingType
@Target({METHOD, TYPE})
@Retention(RUNTIME)
public @interface Secure {
@NonBinding String[] rolesAllowed() default {};
}
Usually we use combinations of interceptor bindings types to bind multiple interceptors to a Web Bean. For example, the following declaration would be used to bind TransactionInterceptor
and SecurityInterceptor
to the same Web Bean:
@Secure(rolesAllowed="admin") @Transactional
public class ShoppingCart { ... }
However, in very complex cases, an interceptor itself may specify some combination of interceptor binding types:
@Transactional @Secure @Interceptor
public class TransactionalSecureInterceptor { ... }
Then this interceptor could be bound to the checkout()
method using any one of the following combinations:
public class ShoppingCart {
@Transactional @Secure public void checkout() { ... }
}
@Secure
public class ShoppingCart {
@Transactional public void checkout() { ... }
}
@Transactionl
public class ShoppingCart {
@Secure public void checkout() { ... }
}
@Transactional @Secure
public class ShoppingCart {
public void checkout() { ... }
}
One limitation of the Java language support for annotations is the lack of annotation inheritance. Really, annotations should have reuse built in, to allow this kind of thing to work:
public @interface Action extends Transactional, Secure { ... }
Well, fortunately, Web Beans works around this missing feature of Java. We may annotate one interceptor binding type with other interceptor binding types. The interceptor bindings are transitiveany Web Bean with the first interceptor binding inherits the interceptor bindings declared as meta-annotations.
@Transactional @Secure
@InterceptorBindingType
@Target(TYPE)
@Retention(RUNTIME)
public @interface Action { ... }
Any Web Bean annotated @Action
will be bound to both TransactionInterceptor
and SecurityInterceptor
. (And even TransactionalSecureInterceptor
, if it exists.)
The @Interceptors
annotation defined by the EJB specification is supported for both enterprise and simple Web Beans, for example:
@Interceptors({TransactionInterceptor.class, SecurityInterceptor.class})
public class ShoppingCart {
public void checkout() { ... }
}
However, this approach suffers the following drawbacks:
the interceptor implementation is hardcoded in business code,
interceptors may not be easily disabled at deployment time, and
the interceptor ordering is non-globalit is determined by the order in which interceptors are listed at the class level.
Therefore, we recommend the use of Web Beans-style interceptor bindings.
Gli interceptor sono un potente modo per catturare e separare i concern (N.d.T. un concern è un particulare concetto o area di interesse) che sono orthogonal al sistema tipo. Qualsiasi interceptor è capace di intercettare le invocazioni di qualsiasi tipo Java. Questo li rende perfetti per risolvere concern tecnici quali gestione delle transazioni e la sicurezza. Comunque, per natura, gli interceptor non sono consapevoli dell'attuale semantica degli eventi che intercettano. Quindi gli interceptor non sono il giusto strumento per separare i concern di tipo business.
Il contrario è vero per i decoratori. Un decoratore intercetta le invocazioni solamente per una certa interfaccia Java, e quindi è consapevole della semantica legata a questa. Ciò rende i decoratori uno strumento perfetto per modellare alcuni tipi di concern di business. E significa pure che un decoratore non ha la generalità di un interceptor. I decoratori non sono capaci di risolvere i concern tecnici che agiscono per diversi tipi.
Supponiamo di avere un'interfaccia che rappresenti degli account:
public interface Account {
public BigDecimal getBalance();
public User getOwner();
public void withdraw(BigDecimal amount);
public void deposit(BigDecimal amount);
}
Parecchi Web Beans del nostro sistema implementano l'interfaccia Account
. Abbiamo come comune requisito legale, per ogni tipo di account, che le transazioni lunghe vengano registrate dal sistema in uno speciale log. Questo è un lavoro perfetto per un decoratore.
Un decorator è un semplice Web Beans che implementa il tipo che decora ed è annotato con @Decorator
."
@Decorator
public abstract class LargeTransactionDecorator
implements Account {
@Decorates Account account;
@PersistenceContext EntityManager em;
public void withdraw(BigDecimal amount) {
account.withdraw(amount);
if ( amount.compareTo(LARGE_AMOUNT)
>0 ) {
em.persist( new LoggedWithdrawl(amount) );
}
}
public void deposit(BigDecimal amount);
account.deposit(amount);
if ( amount.compareTo(LARGE_AMOUNT)
>0 ) {
em.persist( new LoggedDeposit(amount) );
}
}
}
Diversamente dai semplici Web Beans, un decoratore può essere una classe astratta. Se un decoratore non ha niente da fare per un particolare metodo, allora non occorre implementare quel metodo.
Tutti i decoratori hanno un attributo delegato. Il tipo ed i tipi di binding dell'attributo delegato determinano a quali Web Beans è legato il decoratore. Il tipo di attributo delegato deve implementare o estendere tutte le interfacce implementate dal decoratore.
Quest'attributo delegate specifica che ildecorator è legao a tutti i Web Beans che implementano Account
:
@Decorates Account account;
Un attributo delegato può specificare un'annotazione di binding. E quindi il decoratore verrà associato a Web Beans con lo stesso binding.
@Decorates @Foreign Account account;
Un decorator è legato ad un qualsiasi Web Bean che:
ha il tipo di attributo delegate come un tipo API, e
ha tutti i tipi di binding che sono dichiarati dall'attributo delegate.
Il decoratore può invocare l'attributo delegate, il ché ha lo stesso effetto come chiamare InvocationContext.proceed()
da un interceptor.
Occorre abilitare il decoratore in web-beans.xml
.
<Decorators>
<myapp:LargeTransactionDecorator/>
</Decorators
>
Per i decoratori questa dichiarazione provvede alle stesse finalità di quanto la dichiarazione <Interceptors>
fa per gli interceptor.
Consente di specificare un ordinamento totale per tutti i decoratori del sistema, assicurando un comportamento deterministico, e
consente di abilitare o disabilitare le classi decorato durante la fase di deploy.
Gli interceptor per un metodo sono chiamati prima dei decoratori che vengono applicati a tali metodo.
Il sistema di notifica a eventi di Web Beans consente a Web Beans di interagire in maniera totalmente disaccoppiata. I produttori di eventi sollevano eventi che vengono consegnati agli osservatori di eventi tramite il manager Web Bean. Lo schema base può suonare simile al familiare pattern observer/observable, ma ci sono un paio di differenze:
non solo i produttori di eventi sono disaccoppiati dagli osservatori; gli osservatori sono completamente disaccoppiati dai produttori,
gli osservatori possono specificare una combinazione di "selettori" per restringere il set di notifiche di eventi da ricevere, e
gli osservatori possono essere notificati immediatamente, o possono specificare che la consegna degli eventi venga ritardata fino alla fine della transazione conrrente
Un metodo osservatore è un metodo di un Web Bean con un parametro annotato @Observes
.
public void onAnyDocumentEvent(@Observes Document document) { ... }
Il parametro annotato viene chiamato parametro evento. Il tipo di parametro evento è il tipo evento osservato. I metodi osservatori possono anche specificare dei "selettori", che sono solo istanze di tipi di binding di Web Beans. Quando un tipo di binding viene usato come selettore di eventi viene chiamato tipo binding di evento.
@BindingType
@Target({PARAMETER, FIELD})
@Retention(RUNTIME)
public @interface Updated { ... }
Specifichiamo i binding di evento del metodo osservatore annotando il parametro evento:
public void afterDocumentUpdate(@Observes @Updated Document document) { ... }
Un metodo osservatore non ha bisogno di specificare alcun binding di eventoin questo caso è interessato a tutti gli eventi di un particolare tipo. Se specifica dei binding di evento, è solamente interessato agli eventi che hanno anche gli stessi binding di evento.
Il metodo osservatore può avere parametri addizionali che vengono iniettati secondo la solita semantica di iniezione del parametro del metodo Web Beans.
public void afterDocumentUpdate(@Observes @Updated Document document, User user) { ... }
The event producer may obtain an event notifier object by injection:
@Observable Event<Document
> documentEvent
The @Observable
annotation implicitly defines a Web Bean with scope @Dependent
and deployment type @Standard
, with an implementation provided by the Web Bean manager.
A producer raises events by calling the fire()
method of the Event
interface, passing an event object:
documentEvent.fire(document);
An event object may be an instance of any Java class that has no type variables or wildcard type parameters. The event will be delivered to every observer method that:
has an event parameter to which the event object is assignable, and
specifies no event bindings.
The Web Bean manager simply calls all the observer methods, passing the event object as the value of the event parameter. If any observer method throws an exception, the Web Bean manager stops calling observer methods, and the exception is rethrown by the fire()
method.
To specify a "selector", the event producer may pass an instance of the event binding type to the fire()
method:
documentEvent.fire( document, new AnnotationLiteral<Updated
>(){} );
The helper class AnnotationLiteral
makes it possible to instantiate binding types inline, since this is otherwise difficult to do in Java.
The event will be delivered to every observer method that:
has an event parameter to which the event object is assignable, and
does not specify any event binding except for the event bindings passed to fire()
.
Alternatively, event bindings may be specified by annotating the event notifier injection point:
@Observable @Updated Event<Document
> documentUpdatedEvent
Then every event fired via this instance of Event
has the annotated event binding. The event will be delivered to every observer method that:
has an event parameter to which the event object is assignable, and
does not specify any event binding except for the event bindings passed to fire()
or the annotated event bindings of the event notifier injection point.
It's often useful to register an event observer dynamically. The application may implement the Observer
interface and register an instance with an event notifier by calling the observe()
method.
documentEvent.observe( new Observer<Document
>() { public void notify(Document doc) { ... } } );
Event binding types may be specified by the event notifier injection point or by passing event binding type instances to the observe()
method:
documentEvent.observe( new Observer<Document
>() { public void notify(Document doc) { ... } },
new AnnotationLiteral<Updated
>(){} );
An event binding type may have annotation members:
@BindingType
@Target({PARAMETER, FIELD})
@Retention(RUNTIME)
public @interface Role {
RoleType value();
}
The member value is used to narrow the messages delivered to the observer:
public void adminLoggedIn(@Observes @Role(ADMIN) LoggedIn event) { ... }
Event binding type members may be specified statically by the event producer, via annotations at the event notifier injection point:
@Observable @Role(ADMIN) Event<LoggedIn
> LoggedInEvent;}}
Alternatively, the value of the event binding type member may be determined dynamically by the event producer. We start by writing an abstract subclass of AnnotationLiteral
:
abstract class RoleBinding
extends AnnotationLiteral<Role
>
implements Role {}
The event producer passes an instance of this class to fire()
:
documentEvent.fire( document, new RoleBinding() { public void value() { return user.getRole(); } } );
Event binding types may be combined, for example:
@Observable @Blog Event<Document
> blogEvent;
...
if (document.isBlog()) blogEvent.fire(document, new AnnotationLiteral<Updated
>(){});
When this event occurs, all of the following observer methods will be notified:
public void afterBlogUpdate(@Observes @Updated @Blog Document document) { ... }
public void afterDocumentUpdate(@Observes @Updated Document document) { ... }
public void onAnyBlogEvent(@Observes @Blog Document document) { ... }
public void onAnyDocumentEvent(@Observes Document document) { ... }}}
Transactional observers receive their event notifications during the before or after completion phase of the transaction in which the event was raised. For example, the following observer method needs to refresh a query result set that is cached in the application context, but only when transactions that update the Category
tree succeed:
public void refreshCategoryTree(@AfterTransactionSuccess @Observes CategoryUpdateEvent event) { ... }
There are three kinds of transactional observers:
@AfterTransactionSuccess
observers are called during the after completion phase of the transaction, but only if the transaction completes successfully
@AfterTransactionFailure
observers are called during the after completion phase of the transaction, but only if the transaction fails to complete successfully
@AfterTransactionCompletion
observers are called during the after completion phase of the transaction
@BeforeTransactionCompletion
observers are called during the before completion phase of the transaction
Transactional observers are very important in a stateful object model like Web Beans, because state is often held for longer than a single atomic transaction.
Si immagini di avere cachato un risultato di query JPA nello scope di applicazione:
@ApplicationScoped @Singleton
public class Catalog {
@PersistenceContext EntityManager em;
List<Product
> products;
@Produces @Catalog
List<Product
> getCatalog() {
if (products==null) {
products = em.createQuery("select p from Product p where p.deleted = false")
.getResultList();
}
return products;
}
}
Di tanto in tanto un Product
viene creato o cancellato. Quando questo avviene occorre aggiornare il catalogo del Product
. Ma si dovrebbe aspettare che la transazione abbia completato con successo prima di eseguire l'aggiornamento!
The Web Bean that creates and deletes Product
s could raise events, for example:
@Stateless
public class ProductManager {
@PersistenceContext EntityManager em;
@Observable Event<Product
> productEvent;
public void delete(Product product) {
em.delete(product);
productEvent.fire(product, new AnnotationLiteral<Deleted
>(){});
}
public void persist(Product product) {
em.persist(product);
productEvent.fire(product, new AnnotationLiteral<Created
>(){});
}
...
}
And now Catalog
can observe the events after successful completion of the transaction:
@ApplicationScoped @Singleton
public class Catalog {
...
void addProduct(@AfterTransactionSuccess @Observes @Created Product product) {
products.add(product);
}
void addProduct(@AfterTransactionSuccess @Observes @Deleted Product product) {
products.remove(product);
}
}
The second major theme of Web Beans is strong typing. The information about the dependencies, interceptors and decorators of a Web Bean, and the information about event consumers for an event producer, is contained in typesafe Java constructs that may be validated by the compiler.
You don't see string-based identifiers in Web Beans code, not because the framework is hiding them from you using clever defaulting rulesso-called "configuration by convention"but because there are simply no strings there to begin with!
The obvious benefit of this approach is that any IDE can provide autocompletion, validation and refactoring without the need for special tooling. But there is a second, less-immediately-obvious, benefit. It turns out that when you start thinking of identifying objects, events or interceptors via annotations instead of names, you have an opportunity to lift the semantic level of your code.
Web Beans encourages you develop annotations that model concepts, for example,
@Asynchronous
,
@Mock
,
@Secure
or
@Updated
,
instead of using compound names like
asyncPaymentProcessor
,
mockPaymentProcessor
,
SecurityInterceptor
or
DocumentUpdatedEvent
.
The annotations are reusable. They help describe common qualities of disparate parts of the system. They help us categorize and understand our code. They help us deal with common concerns in a common way. They make our code more literate and more understandable.
Web Beans stereotypes take this idea a step further. A stereotype models a common role in your application architecture. It encapsulates various properties of the role, including scope, interceptor bindings, deployment type, etc, into a single reusable package.
Even Web Beans XML metadata is strongly typed! There's no compiler for XML, so Web Beans takes advantage of XML schemas to validate the Java types and attributes that appear in XML. This approach turns out to make the XML more literate, just like annotations made our Java code more literate.
We're now ready to meet some more advanced features of Web Beans. Bear in mind that these features exist to make our code both easier to validate and more understandable. Most of the time you don't ever really need to use these features, but if you use them wisely, you'll come to appreciate their power.
Secondo la specifica Web Beans:
In many systems, use of architectural patterns produces a set of recurring Web Bean roles. A stereotype allows a framework developer to identify such a role and declare some common metadata for Web Beans with that role in a central place.
A stereotype encapsulates any combination of:
a default deployment type,
a default scope type,
a restriction upon the Web Bean scope,
a requirement that the Web Bean implement or extend a certain type, and
a set of interceptor binding annotations.
A stereotype may also specify that all Web Beans with the stereotype have defaulted Web Bean names.
A Web Bean may declare zero, one or multiple stereotypes.
A stereotype is a Java annotation type. This stereotype identifies action classes in some MVC framework:
@Retention(RUNTIME)
@Target(TYPE)
@Stereotype
public @interface Action {}
We use the stereotype by applying the annotation to a Web Bean.
@Action
public class LoginAction { ... }
A stereotype may specify a default scope and/or default deployment type for Web Beans with that stereotype. For example, if the deployment type @WebTier
identifies Web Beans that should only be deployed when the system executes as a web application, we might specify the following defaults for action classes:
@Retention(RUNTIME)
@Target(TYPE)
@RequestScoped
@WebTier
@Stereotype
public @interface Action {}
Of course, a particular action may still override these defaults if necessary:
@Dependent @Mock @Action
public class MockLoginAction { ... }
If we want to force all actions to a particular scope, we can do that too.
Suppose that we wish to prevent actions from declaring certain scopes. Web Beans lets us explicitly specify the set of allowed scopes for Web Beans with a certain stereotype. For example:
@Retention(RUNTIME)
@Target(TYPE)
@RequestScoped
@WebTier
@Stereotype(supportedScopes=RequestScoped.class)
public @interface Action {}
If a particular action class attempts to specify a scope other than the Web Beans request scope, an exception will be thrown by the Web Bean manager at initialization time.
We can also force all Web Bean with a certain stereotype to implement an interface or extend a class:
@Retention(RUNTIME)
@Target(TYPE)
@RequestScoped
@WebTier
@Stereotype(requiredTypes=AbstractAction.class)
public @interface Action {}
If a particular action class does not extend the class AbstractAction
, an exception will be thrown by the Web Bean manager at initialization time.
A stereotype may specify a set of interceptor bindings to be inherited by all Web Beans with that stereotype.
@Retention(RUNTIME)
@Target(TYPE)
@RequestScoped
@Transactional(requiresNew=true)
@Secure
@WebTier
@Stereotype
public @interface Action {}
This helps us get technical concerns even further away from the business code!
Finally, we can specify that all Web Beans with a certain stereotype have a Web Bean name, defaulted by the Web Bean manager. Actions are often referenced in JSP pages, so they're a perfect use case for this feature. All we need to do is add an empty @Named
annotation:
@Retention(RUNTIME)
@Target(TYPE)
@RequestScoped
@Transactional(requiresNew=true)
@Secure
@Named
@WebTier
@Stereotype
public @interface Action {}
Now, LoginAction
will have the name loginAction
.
We've already met two standard stereotypes defined by the Web Beans specification: @Interceptor
and @Decorator
.
Web Beans defines one further standard stereotype:
@Named
@RequestScoped
@Stereotype
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @interface Model {}
This stereotype is intended for use with JSF. Instead of using JSF managed beans, just annotate a Web Bean @Model
, and use it directly in your JSF page.
We've already seen how the Web Beans dependency injection model lets us override the implementation of an API at deployment time. For example, the following enterprise Web Bean provides an implementation of the API PaymentProcessor
in production:
@CreditCard @Stateless
public class CreditCardPaymentProcessor
implements PaymentProcessor {
...
}
But in our staging environment, we override that implementation of PaymentProcessor
with a different Web Bean:
@CreditCard @Stateless @Staging
public class StagingCreditCardPaymentProcessor
implements PaymentProcessor {
...
}
What we've tried to do with StagingCreditCardPaymentProcessor
is to completely replace AsyncPaymentProcessor
in a particular deployment of the system. In that deployment, the deployment type @Staging
would have a higher priority than the default deployment type @Production
, and therefore clients with the following injection point:
@CreditCard PaymentProcessor ccpp
Would receive an instance of StagingCreditCardPaymentProcessor
.
Sfortunatamente ci sono parecchie trappole in cui è facile cadere:
the higher-priority Web Bean may not implement all the API types of the Web Bean that it attempts to override,
the higher-priority Web Bean may not declare all the binding types of the Web Bean that it attempts to override,
the higher-priority Web Bean might not have the same name as the Web Bean that it attempts to override, or
the Web Bean that it attempts to override might declare a producer method, disposal method or observer method.
In each of these cases, the Web Bean that we tried to override could still be called at runtime. Therefore, overriding is somewhat prone to developer error.
Web Beans provides a special feature, called specialization, that helps the developer avoid these traps. Specialization looks a little esoteric at first, but it's easy to use in practice, and you'll really appreciate the extra security it provides.
Specialization is a feature that is specific to simple and enterprise Web Beans. To make use of specialization, the higher-priority Web Bean must:
essere un diretta sottoclasse del Web Bean di cui fa l'override, e
essere un semplice Web Bean se il Web Bean di cui fare override è un semplice Web Bean o un Web Bean Enterprise se il Web Bean di cui fa override è un Web Bean Enterprise, e
essere annotato con @Specializes
.
@Stateless @Staging @Specializes
public class StagingCreditCardPaymentProcessor
extends CreditCardPaymentProcessor {
...
}
We say that the higher-priority Web Bean specializes its superclass.
Quando viene usata la specializzazione:
the binding types of the superclass are automatically inherited by the Web Bean annotated @Specializes
, and
the Web Bean name of the superclass is automatically inherited by the Web Bean annotated @Specializes
, and
producer methods, disposal methods and observer methods declared by the superclass are called upon an instance of the Web Bean annotated @Specializes
.
In our example, the binding type @CreditCard
of CreditCardPaymentProcessor
is inherited by StagingCreditCardPaymentProcessor
.
Furthermore, the Web Bean manager will validate that:
all API types of the superclass are API types of the Web Bean annotated @Specializes
(all local interfaces of the superclass enterprise bean are also local interfaces of the subclass),
the deployment type of the Web Bean annotated @Specializes
has a higher precedence than the deployment type of the superclass, and
there is no other enabled Web Bean that also specializes the superclass.
If any of these conditions are violated, the Web Bean manager throws an exception at initialization time.
Therefore, we can be certain that the superclass with never be called in any deployment of the system where the Web Bean annotated @Specializes
is deployed and enabled.
Finora abbiamo visto molti esempi di Web Bean dichiarati usando annotazioni. Comunque ci sono varie occasioni in cui non è possibile usare le annotazioni per definire un Web Bean:
when the implementation class comes from some preexisting library, or
when there should be multiple Web Beans with the same implementation class.
In either of these cases, Web Beans gives us two options:
write a producer method, or
declare the Web Bean using XML.
Many frameworks use XML to provide metadata relating to Java classes. However, Web Beans uses a very different approach to specifying the names of Java classes, fields or methods to most other frameworks. Instead of writing class and member names as the string values of XML elements and attributes, Web Beans lets you use the class or member name as the name of the XML element.
The advantage of this approach is that you can write an XML schema that prevents spelling errors in your XML document. It's even possible for a tool to generate the XML schema automatically from the compiled Java code. Or, an integrated development environment could perform the same validation without the need for the explicit intermediate generation step.
For each Java package, Web Beans defines a corresponding XML namespace. The namespace is formed by prepending urn:java:
to the Java package name. For the package com.mydomain.myapp
, the XML namespace is urn:java:com.mydomain.myapp
.
Java types belonging to a package are referred to using an XML element in the namespace corresponding to the package. The name of the element is the name of the Java type. Fields and methods of the type are specified by child elements in the same namespace. If the type is an annotation, members are specified by attributes of the element.
Per esempio l'elemento <util:Date/>
nel seguente frammento XML si riferisce alla classe java.util.Date
:
<WebBeans xmlns="urn:java:javax.webbeans"
xmlns:util="urn:java:java.util">
<util:Date/>
</WebBeans
>
And this is all the code we need to declare that Date
is a simple Web Bean! An instance of Date
may now be injected by any other Web Bean:
@Current Date date
We can declare the scope, deployment type and interceptor binding types using direct child elements of the Web Bean declaration:
<myapp:ShoppingCart>
<SessionScoped/>
<myfwk:Transactional requiresNew="true"/>
<myfwk:Secure/>
</myapp:ShoppingCart
>
We use exactly the same approach to specify names and binding type:
<util:Date>
<Named
>currentTime</Named>
</util:Date>
<util:Date>
<SessionScoped/>
<myapp:Login/>
<Named
>loginTime</Named>
</util:Date>
<util:Date>
<ApplicationScoped/>
<myapp:SystemStart/>
<Named
>systemStartTime</Named>
</util:Date
>
Where @Login
and @SystemStart
are binding annotations types.
@Current Date currentTime;
@Login Date loginTime;
@SystemStart Date systemStartTime;
As usual, a Web Bean may support multiple binding types:
<myapp:AsynchronousChequePaymentProcessor>
<myapp:PayByCheque/>
<myapp:Asynchronous/>
</myapp:AsynchronousChequePaymentProcessor
>
Interceptors and decorators are just simple Web Beans, so they may be declared just like any other simple Web Bean:
<myfwk:TransactionInterceptor>
<Interceptor/>
<myfwk:Transactional/>
</myfwk:TransactionInterceptor
>
Web Beans lets us define a Web Bean at an injection point. For example:
<myapp:System>
<ApplicationScoped/>
<myapp:admin>
<myapp:Name>
<myapp:firstname
>Gavin</myapp:firstname>
<myapp:lastname
>King</myapp:lastname>
<myapp:email
>gavin@hibernate.org</myapp:email>
</myapp:Name>
</myapp:admin>
</myapp:System
>
The <Name>
element declares a simple Web Bean of scope @Dependent
and class Name
, with a set of initial field values. This Web Bean has a special, container-generated binding and is therefore injectable only to the specific injection point at which it is declared.
This simple but powerful feature allows the Web Beans XML format to be used to specify whole graphs of Java objects. It's not quite a full databinding solution, but it's close!
If we want our XML document format to be authored by people who aren't Java developers, or who don't have access to our code, we need to provide a schema. There's nothing specific to Web Beans about writing or using the schema.
<WebBeans xmlns="urn:java:javax.webbeans"
xmlns:myapp="urn:java:com.mydomain.myapp"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:java:javax.webbeans http://java.sun.com/jee/web-beans-1.0.xsd
urn:java:com.mydomain.myapp http://mydomain.com/xsd/myapp-1.2.xsd">
<myapp:System>
...
</myapp:System>
</WebBeans
>
Writing an XML schema is quite tedious. Therefore, the Web Beans RI project will provide a tool which automatically generates the XML schema from compiled Java code.
The third theme of Web Beans is integration. Web Beans was designed to work in concert with other technologies, helping the application developer fit the other technologies together. Web Beans is an open technology. It forms a part of the Java EE ecosystem, and is itself the foundation for a new ecosystem of portable extensions and integration with existing frameworks and technologies.
We've already seen how Web Beans helps integrate EJB and JSF, allowing EJBs to be bound directly to JSF pages. That's just the beginning. Web Beans offers the same potential to diverse other technologies, such as Business Process Management engines, other Web Frameworks, and third-party component models. The Java EE platform will never be able to standardize all the interesting technologies that are used in the world of Java application development, but Web Beans makes it easier to use the technologies which are not yet part of the platform seamlessly within the Java EE environment.
We're about to see how to take full advantage of the Java EE platform in an application that uses Web Beans. We'll also briefly meet a set of SPIs that are provided to support portable extensions to Web Beans. You might not ever need to use these SPIs directly, but it's nice to know they are there if you need them. Most importantly, you'll take advantage of them indirectly, every time you use a third-party extension.
Web Beans è pienamente integrata nell'ambiente Java EE. Web Beans ha accesso alle risorse Java EE ed ai contesti di persistenza JPA. I Web Beans possono essere usati in espressioni Unified EL dentro pagine JSF e JSP. Possono anche essere iniettati negli oggetti, come Servlet e Message-Driven Beans, che non sono Web Beans.
Tutti i Web Beans sia semplici che enterprise si avvantaggiano della dependency injection di Java EE usando @Resource
, @EJB
e @PersistenceContext
. Abbiamo già visto un paio di esempi a riguardo, sebbene non ci siamo soffermati molto a suo tempo.
@Transactional @Interceptor
public class TransactionInterceptor {
@Resource Transaction transaction;
@AroundInvoke public Object manageTransaction(InvocationContext ctx) { ... }
}
@SessionScoped
public class Login {
@Current Credentials credentials;
@PersistenceContext EntityManager userDatabase;
...
}
Le chiamate Java EE @PostConstruct
e @PreDestroy
vengono anche supportate per tutti i Web Beans (semplici e enterprise). Il metodo @PostConstruct
viene chiamato dopo che tutta l'injection è stata eseguita.
C'è una restrizione di cui essere informati: @PersistenceContext(type=EXTENDED)
non è supportato per i Web Beans semplici.
E' facile utilizzare i Web Beans da un Servlet in Java EE 6. Semplicemente si inietti il Web Bean utilizzando l'injection del campo Web Bean o del metodo inizializzatore.
public class Login extends HttpServlet {
@Current Credentials credentials;
@Current Login login;
@Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
credentials.setUsername( request.getAttribute("username") ):
credentials.setPassword( request.getAttribute("password") ):
login.login();
if ( login.isLoggedIn() ) {
response.sendRedirect("/home.jsp");
}
else {
response.sendRedirect("/loginError.jsp");
}
}
}
Il client proxy Web Beans si occupa di instradare le invocazioni dei metodi da un Servlet alle corrette istanze di Credentials
e Login
per la richiesta corrente e la sessione HTTP.
L'injection dei Web Beans si applica a tutti gli EJB3, perfino quando non sono sotto il controllo del manager Web Bean (per esempio se sono stati ottenuti da ricerca JNDI diretta, o injection usando @EJB
) In particolaresi può usare l'injection di Web Beans nei Message-Driven Beans, che non sono considerati Web Beans poiché non possono essere iniettati.
Si possono perfino associare degli interceptor Web Beans ai Message-Driven Beans.
@Transactional @MessageDriven
public class ProcessOrder implements MessageListener {
@Current Inventory inventory;
@PersistenceContext EntityManager em;
public void onMessage(Message message) {
...
}
}
Quindi ricevere i messaggi è veramente facile in ambiente Web Beans. Ma attenzione che non è disponibile alcun contesto di sessione o conversazione quando il messaggio viene consegnato al Message-Driven Bean. Solamente i Web Beans @RequestScoped
and @ApplicationScoped
sono disponibili.
E' anche molto facile spedire messaggi usando Web Beans.
La spedizione dei messaggi usando JMS può essere abbastanza complessa, a causa del numero di oggetti differenti da trattare. Per le code si hanno Queue
, QueueConnectionFactory
, QueueConnection
, QueueSession
e QueueSender
. Per i topic si hanno Topic
, TopicConnectionFactory
, TopicConnection
, TopicSession
e TopicPublisher
. Ciascuno di questi oggetti ha il proprio ciclo di vita e modello di thread di cui bisogna (pre)occuparsi.
I Web Beans si prendono cura di tutto questo per noi. Tutto ciò che occorre fare è dichiarare la coda od il topic in web-beans.xml
, specificando un
<Queue>
<destination
>java:comp/env/jms/OrderQueue</destination>
<connectionFactory
>java:comp/env/jms/QueueConnectionFactory</connectionFactory>
<myapp:OrderProcessor/>
</Queue
>
<Topic>
<destination
>java:comp/env/jms/StockPrices</destination>
<connectionFactory
>java:comp/env/jms/TopicConnectionFactory</connectionFactory>
<myapp:StockPrices/>
</Topic
>
Ora è possibile iniettare Queue
, QueueConnection
, QueueSession
o QueueSender
per una coda, oppure Topic
, TopicConnection
, TopicSession
o TopicPublisher
per un topic.
@OrderProcessor QueueSender orderSender;
@OrderProcessor QueueSession orderSession;
public void sendMessage() {
MapMessage msg = orderSession.createMapMessage();
...
orderSender.send(msg);
}
@StockPrices TopicPublisher pricePublisher;
@StockPrices TopicSession priceSession;
public void sendMessage(String price) {
pricePublisher.send( priceSession.createTextMessage(price) );
}
The lifecycle of the injected JMS objects is completely controlled by the Web Bean manager.
Web Beans non definisce nessuno archivio speciale per il deploy. Si può impacchettare i Web Beans in JAR, EJB-JAR o WARqualsiasi locazione di deploy nel classpath dell'applicazione. Comunque ciascun archivio che contiene Web Beans devi includere un file chiamato web-beans.xml
nella directory META-INF
o WEB-INF
. Il file può essere vuoto. I Web Beans collocati negli archivi che non hanno un file web-beans.xml
non saranno disponibili per l'uso nell'applicazione.
Per l'esecuzione in Java SE, Web Beans può essere deployato in un qualsiasi posto nel quale gli EJB siano stati messi per essere eseguito da un embeddable EJB Lite container. Di nuovo ogni locazioni deve contenere un file web-beans.xml
.
Web Beans è inteso essere una piattaforma per framework, estensioni e integrazione con altre tecnologie. Quindi Web Beans espone un set di SPI (Service Provider Interface) per l'uso da parte degli sviluppatori di estensioni portabili a Web Beans. Per esempio, i seguentitipi di estensione sono state prese in considerazione dai progettisti di Web Beans:
Integrazione con i motori di Gestione dei Processi di Business,
integrazione con framework di terze-parti quali Spring, Seam, GWT o Wicket, e
nuova tecnologia basata sul modello di programmazione di Web Beans.
Il nervo centrale per l'estensione di Web Beans è l'oggetto Manager
.
L'interfaccia Manager
consente di registrare ed ottenere programmaticamente interceptor, decoratori, osservatori e contesti di Web Beans.
public interface Manager
{
public <T
> Set<Bean<T
>
> resolveByType(Class<T
> type, Annotation... bindings);
public <T
> Set<Bean<T
>
> resolveByType(TypeLiteral<T
> apiType,
Annotation... bindings);
public <T
> T getInstanceByType(Class<T
> type, Annotation... bindings);
public <T
> T getInstanceByType(TypeLiteral<T
> type,
Annotation... bindings);
public Set<Bean<?>
> resolveByName(String name);
public Object getInstanceByName(String name);
public <T
> T getInstance(Bean<T
> bean);
public void fireEvent(Object event, Annotation... bindings);
public Context getContext(Class<? extends Annotation
> scopeType);
public Manager addContext(Context context);
public Manager addBean(Bean<?> bean);
public Manager addInterceptor(Interceptor interceptor);
public Manager addDecorator(Decorator decorator);
public <T
> Manager addObserver(Observer<T
> observer, Class<T
> eventType,
Annotation... bindings);
public <T
> Manager addObserver(Observer<T
> observer, TypeLiteral<T
> eventType,
Annotation... bindings);
public <T
> Manager removeObserver(Observer<T
> observer, Class<T
> eventType,
Annotation... bindings);
public <T
> Manager removeObserver(Observer<T
> observer,
TypeLiteral<T
> eventType, Annotation... bindings);
public <T
> Set<Observer<T
>
> resolveObservers(T event, Annotation... bindings);
public List<Interceptor
> resolveInterceptors(InterceptionType type,
Annotation... interceptorBindings);
public List<Decorator
> resolveDecorators(Set<Class<?>
> types,
Annotation... bindings);
}
Possiamo ottenere un'istanza di Manager
via iniezione:
@Current Manager manager
Istanze della classe astratta Bean
rappresentano i Web Beans. C'è un'istanza di Bean
registrata con l'oggetto Manager
per ogni Web Bean dell'applicazione.
public abstract class Bean<T> {
private final Manager manager;
protected Bean(Manager manager) {
this.manager=manager;
}
protected Manager getManager() {
return manager;
}
public abstract Set<Class> getTypes();
public abstract Set<Annotation> getBindingTypes();
public abstract Class<? extends Annotation> getScopeType();
public abstract Class<? extends Annotation> getDeploymentType();
public abstract String getName();
public abstract boolean isSerializable();
public abstract boolean isNullable();
public abstract T create();
public abstract void destroy(T instance);
}
E' possibile estendere la classe Bean
e registrare le istanze chiamando Manager.addBean()
per fornire supporto a nuovi tipi di Web Beans, oltre a quelli definiti dalla specifica Web Beans (semplici ed enterprise, metodi produttori e endpoint JMS). Per esempio possiamo usare la classe Bean
per consentire ad oggetti gestiti da altri framework di essere iniettati nei Web Beans.
Ci sono due sottoclassi di Bean
definite dalla specifica Web Beans: Interceptor
e Decorator
.
L'interfaccia Context
supporta l'aggiunta di nuovi scope ai Web Beans, o l'estensione di scope esistenti a nuovi ambienti.
public interface Context {
public Class<? extends Annotation> getScopeType();
public <T> T get(Bean<T> bean, boolean create);
boolean isActive();
}
Per esempio possiamo implementare Context
per aggiungere uno scope di tipo business process a Web Beans, o per aggiungere il supporto allo scope di conversazione ad un'applicazione che impiega Wicket.
Poiché Web Beans è così nuova, non è ancora disponibile molta informazione online.
La specifica Web Beans è sicuramente la migliore fonte per avere informazioni su Web Beans. La specifica è lunga circa 100 pagine, circa quest'articolo e per lo più leggibile altrettanto facilmente. Ma sicuramente copre molti dettagli che sono stati saltati nel presente documento. La specifica è disponibile al seguente indirizzo http://jcp.org/en/jsr/detail?id=299
.
L'implementazione della documentazione Web Beans è stata sviluppata in http://seamframework.org/WebBeans
. Il team di sviluppo di RI ed il blog per la specifica Web Beans si trova in http://in.relation.to
. Quest'articolo è sostanzialmente basato su una serie di articoli pubblicati sul blog.
Currently the Web Beans RI only runs in JBoss AS 5; integrating the RI into other EE environments (for example another application server like Glassfish), into a servlet container (like Tomcat), or with an Embedded EJB3.1 implementation is fairly easy. In this Appendix we will briefly discuss the steps needed.
It should be possible to run Web Beans in an SE environment, but you'll to do more work, adding your own contexts and lifecycle. The Web Beans RI currently doesn't expose lifecycle extension points, so you would have to code directly against Web Beans RI classes.
The Web Beans SPI is located in webbeans-ri-spi
module, and packaged as webbeans-ri-spi.jar
.
Currently, the only SPI to implement is the bootstrap spi:
public interface WebBeanDiscovery {
/**
* Gets list of all classes in classpath archives with web-beans.xml files
*
* @return An iterable over the classes
*/
public Iterable<Class<?>
> discoverWebBeanClasses();
/**
* Gets a list of all web-beans.xml files in the app classpath
*
* @return An iterable over the web-beans.xml files
*/
public Iterable<URL
> discoverWebBeansXml();
/**
* Gets a descriptor for each EJB in the application
*
* @return The bean class to descriptor map
*/
public Iterable<EjbDescriptor<?>
> discoverEjbs();
}
The discovery of Web Bean classes and web-bean.xml
files is self-explanatory (the algorithm is described in Section 11.1 of the JSR-299 specification, and isn't repeated here).
The Web Beans RI also delegates EJB3 bean discovery to the container so that it doesn't have to scan for EJB3 annotations or parse ejb-jar.xml
. For each EJB in the application an EJBDescriptor should be discovered:
public interface EjbDescriptor<T
> {
/**
* Gets the EJB type
*
* @return The EJB Bean class
*/
public Class<T
> getType();
/**
* Gets the local business interfaces of the EJB
*
* @return An iterator over the local business interfaces
*/
public Iterable<BusinessInterfaceDescriptor<?>
> getLocalBusinessInterfaces();
/**
* Gets the remote business interfaces of the EJB
*
* @return An iterator over the remote business interfaces
*/
public Iterable<BusinessInterfaceDescriptor<?>
> getRemoteBusinessInterfaces();
/**
* Get the remove methods of the EJB
*
* @return An iterator over the remove methods
*/
public Iterable<MethodDescriptor
> getRemoveMethods();
/**
* Indicates if the bean is stateless
*
* @return True if stateless, false otherwise
*/
public boolean isStateless();
/**
* Indicates if the bean is a EJB 3.1 Singleton
*
* @return True if the bean is a singleton, false otherwise
*/
public boolean isSingleton();
/**
* Indicates if the EJB is stateful
*
* @return True if the bean is stateful, false otherwise
*/
public boolean isStateful();
/**
* Indicates if the EJB is and MDB
*
* @return True if the bean is an MDB, false otherwise
*/
public boolean isMessageDriven();
/**
* Gets the EJB name
*
* @return The name
*/
public String getEjbName();
/**
* @return The JNDI string which can be used to lookup a proxy which
* implements all local business interfaces
*
*/
public String getLocalJndiName();
}
The contract described the JavaDoc is enough to implement an EJBDescriptor. In addition to these two interfaces, there is BusinessInterfaceDescriptor
which represents a local business interface (encapsulating the interface class and jndi name), and MethodDescriptor
which encapsulates the method name and parameter types (allowing it to be invoked on any instance of the EJB, proxy or otherwise).
The Web Beans RI can be told to load your implementation of WebBeanDiscovery
using the property org.jboss.webbeans.bootstrap.webBeanDiscovery
with the fully qualified class name as the value. For example:
org.jboss.webbeans.bootstrap.webBeanDiscovery=org.jboss.webbeans.integration.jbossas.WebBeanDiscoveryImpl
The property can either be specified as a system property, or in a properties file META-INF/web-beans-ri.properties
.
There are a number of requirements that the Web Beans RI places on the container for correct functioning that fall outside implementation of APIs
If you are integrating the Web Beans into an environment that supports deployment of applications, you must enable, automatically, or through user configuation, classloader isolation for each Web Beans application
webbeans-ri.jar
If you are integrating the Web Beans into an environment that supports deployment of applications, you must insert the webbeans-ri.jar
into the applications isolated classloader. It cannot be loaded from a shared classloader.