SeamFramework.orgCommunity Documentation
If you are using WildFly 8.0 or better, no additional configuration is required to use Weld (or CDI for that matter).
Weld is also built into GlassFish from V3 onwards. Since GlassFish V3 is the Java EE 6 reference implementation, it must support all features of CDI. What better way for GlassFish to support these features than to use Weld, the CDI reference implementation? Just package up your CDI application and deploy.
While CDI does not require support for servlet environments, Weld can be used in a servlet container, such as Tomcat or Jetty.
There is a major limitation to using a servlet container. Weld doesn't support deploying session beans,
injection using
@EJB
or@PersistenceContext
, or using transactional
events in servlet containers. For enterprise features such as these, you should really be looking at a
Java
EE application server.
Weld can be used as a library in an web application that is deployed to a Servlet container. You should
place
weld-servlet.jar
within the
WEB-INF/lib
directory relative to the web
root.
weld-servlet.jar
is an "uber-jar", meaning it bundles all the bits of Weld and CDI
required for running in a Servlet container, for your convenience. Alternatively, you can use its component
jars. A list of transitive dependencies can be found in the
META-INF/DEPENDENCIES.txt
file
inside the
weld-servlet.jar
artifact.
You also need to explicitly specify the servlet listener (used to boot Weld, and control its interaction with requests) in WEB-INF/web.xml in the web root:
<listener>
<listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
</listener>
Actually you don't have to register this listener in Servlet 3.x compliant containers which support javax.servlet.ServletContainerInitializer
service properly (e.g. Tomcat 7.0.50).
In this case org.jboss.weld.environment.servlet.EnhancedListener
will do all the necessary work automatically, and what is more important -
injection into Listeners will work on some containers as well (see Section 18.3.1, “Tomcat” and Section 18.3.2, “Jetty” for more info).
The downside of javax.servlet.ServletContainerInitializer
approach is that the Weld listener will be added to the end of the ordered list of discovered listeners.
In practice the request and session context will not be active during ServletRequestListener
and HttpSessionListener
notifications.
Fortunately, it's possible to combine the EnhancedListener
and the old Listener
to fix this problem - simply add the old Listener
to the web.xml
as mentioned above.
Note that it must be defined before the listeners using request and session context.
There is quite a special use-case where one more special component must be involved.
If you want the session context to be active during HttpSessionListener.sessionDestroyed()
invocation when the session times out or when all the sessions are destroyed because the deployment is being removed
then org.jboss.weld.servlet.WeldTerminalListener
must be specified as the last one in your web.xml
.
This listener activates the session context before other listeners are invoked (note that the listeners are notified in reverse order when a session is being destroyed).
Since Weld 2.2.0.Final only Tomcat 7 and 8 are supported.
Tomcat has a read-only JNDI, so Weld can't automatically bind the BeanManager extension SPI. To bind
the BeanManager into JNDI, you should populate
META-INF/context.xml
in the web root with
the following contents:
<Context>
<Resource name="BeanManager"
auth="Container"
type="javax.enterprise.inject.spi.BeanManager"
factory="org.jboss.weld.resources.ManagerObjectFactory"/>
</Context>
and make it available to your deployment by adding this to the bottom ofweb.xml
:
<resource-env-ref>
<resource-env-ref-name>BeanManager</resource-env-ref-name>
<resource-env-ref-type>
javax.enterprise.inject.spi.BeanManager
</resource-env-ref-type>
</resource-env-ref>
Tomcat only allows you to bind entries to java:comp/env
, so the BeanManager will be
available at
java:comp/env/BeanManager
Weld also supports Servlet and Filter injection in Tomcat containers. Listener injection should also work on Tomcat 7.0.50 and newer versions.
Since Weld 2.0.2.Final only Jetty 7, 8 and 9 are supported.
To bind the BeanManager into JNDI, you should either populate WEB-INF/jetty-env.xml
with the following contents:
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN"
"http://www.eclipse.org/jetty/configure.dtd">
<Configure id="webAppCtx" class="org.eclipse.jetty.webapp.WebAppContext">
<New id="BeanManager" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg> <Ref id="webAppCtx"/> </Arg>
<Arg>BeanManager</Arg>
<Arg>
<New class="javax.naming.Reference">
<Arg>javax.enterprise.inject.spi.BeanManager</Arg>
<Arg>org.jboss.weld.resources.ManagerObjectFactory</Arg>
<Arg/>
</New>
</Arg>
</New>
</Configure>
Or you can configure a special Servlet listener to bind the BeanManager automatically:
<listener>
<listener-class>org.jboss.weld.environment.servlet.BeanManagerResourceBindingListener</listener-class>
</listener>
Just like in Tomcat, you need to make the BeanManager available to your deployment by adding this to the bottom of
web.xml
:
<resource-env-ref>
<resource-env-ref-name>BeanManager</resource-env-ref-name>
<resource-env-ref-type>
javax.enterprise.inject.spi.BeanManager
</resource-env-ref-type>
</resource-env-ref>
Jetty only allows you to bind entries tojava:comp/env
, so the BeanManager will be
available at
java:comp/env/BeanManager
Weld also supports Servlet and Filter injection in Jetty containers. Listener injection should also work on Jetty 9.1.x and newer versions.
In addition to improved integration of the Enterprise Java stack, the "Contexts and Dependency Injection for the Java EE platform" specification also defines a state of the art typesafe, stateful dependency injection framework, which can prove useful in a wide range of application types. To help developers take advantage of this, Weld provides a simple means for being executed in the Java Standard Edition (SE) environment independently of any Java EE APIs.
When executing in the SE environment the following features of Weld are available:
Managed beans with
@PostConstruct
and
@PreDestroy
lifecycle callbacks
Dependency injection with qualifiers and alternatives
@Application
,
@Dependent
and
@Singleton
scopes
Interceptors and decorators
Stereotypes
Events
Portable extension support
EJB beans are not supported.
Weld provides an extension which will boot a CDI bean manager in Java SE, automatically registering all simple beans found on the classpath. The command line parameters can be injected using either of the following:
@Inject @Parameters List<String> params;
@Inject @Parameters String[] paramsArray;
The second form is useful for compatibility with existing classes.
The command line parameters do not become available for injection until the
ContainerInitialized
event is fired. If you need access to the parameters during
initialization you can do so via the
public static String[] getParameters()
method in
StartMain
.
Here's an example of a simple CDI SE application:
import javax.inject.Singleton;
@Singleton
public class HelloWorld
{
public void printHello(@Observes ContainerInitialized event, @Parameters List<String> parameters) {
System.out.println("Hello " + parameters.get(0));
}
}
CDI 1.1 introduced the bean-discovery-mode
attribute specified in the beans.xml
file. The attribute has 3 possible values:
all
: all the classes from the archive are discovered by Weld.
annotated
: only the classes that declare a bean defining annotation are discovered by Weld.
none
: none of the classes from the archive is discovered by Weld.
Bean discovery mode support depends on the jandex library availability on the classpath. The support is summed up in the table below:
Table 18.1.
Jandex available | Jandex unavailable | |
---|---|---|
All discovery | supported | supported |
Annotated discovery | supported | not supported |
None discovery | supported | supported |
In case the discovery mode is not supported, IllegalStateException
is thrown.
Here's an example of a simple CDI SE application:
CDI SE applications can be bootstrapped in the following ways.
Thanks to the power of CDI's typesafe event model, application developers
need not write any bootstrapping code. The Weld SE module comes
with a built-in main method which will bootstrap CDI for you and
then fire a
ContainerInitialized
event. The entry
point for your application code would therefore be a simple bean which observes
the
ContainerInitialized
event, as in the previous example.
In this case your application can be started by calling the provided main method like so:
java org.jboss.weld.environment.se.StartMain <args>
For added flexibility, CDI SE also comes with a bootstrap API
which can be called from within your application in order to initialize
CDI and obtain references to your application's beans and events. The
API consists of two classes:
Weld
and
WeldContainer
.
public class Weld
{
/** Boots Weld and creates and returns a WeldContainer instance, through which
* beans and events can be accesed. */
public WeldContainer initialize() {...}
/** Convenience method for shutting down the container. */
public void shutdown() {...}
}
public class WeldContainer
{
/** Provides access to all beans within the application. */
public Instance<Object> instance() {...}
/** Provides access to all events within the application. */
public Event<Object> event() {...}
/** Provides direct access to the BeanManager. */
public BeanManager getBeanManager() {...}
}
Here's an example application main method which uses this API
to initialize a bean of typeMyApplicationBean
.
import org.jboss.weld.environment.se.Weld;
public static void main(String[] args) {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
container.instance().select(MyApplicationBean.class).get();
weld.shutdown();
}
Alternatively the application could be started by firing a custom
event which would then be observed by another simple bean. The following
example fires
MyEvent
on startup.
org.jboss.weld.environment.se.Weld;
public static void main(String[] args) {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
container.event().select(MyEvent.class).fire( new MyEvent() );
weld.shutdown();
}
In contrast to Java EE applications, Java SE applications place no restrictions
on developers regarding the creation and usage of threads.
Therefore Weld SE provides a custom scope annotation, @ThreadScoped
,
and corresponding context implementation which can be used to bind bean instances
to the current thread. It is intended to be used in scenarios where you might otherwise
useThreadLocal
, and does in fact use
ThreadLocal
under the hood.
To use the @ThreadScoped
annotation you need to enable the
RunnableDecorator
which 'listens' for all executions of
Runnable.run()
and
decorates them by setting up the thread context beforehand, bound to
the current thread, and destroying the context afterwards.
<beans>
<decorators>
<class>org.jboss.weld.environment.se.threading.RunnableDecorator</class>
</decorator>
</beans>
It is not necessary to use @ThreadScoped
in all
multithreaded applications. The thread context is not intended
as a replacement for defining your own application-specific contexts.
It is generally only useful in situations where you would otherwise
have used ThreadLocal
directly, which are typically rare.
Weld SE comes packaged as a 'shaded' jar which includes the CDI API,
Weld Core and all dependent classes bundled into a single jar. Therefore the
only Weld jar you need on the classpath, in addition to your application's
classes and dependent jars, is the Weld SE jar. If you are working with a pure
Java SE application you launch using java
, this may be simpler
for you.
If you prefer to work with individual dependencies, then you can use the
weld-core
jar which just contains the Weld SE classes.
Of course in this mode you will need to assemble the classpath yourself.
If you work with a dependency management solution such as Maven you can declare a dependency such as:
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se</artifactId>
</dependency>
By default, Weld creates an isolated bean archive instance for each processed archive. The consequence of this approach is the ability to enable Alternatives/Interceptors/Decorators on a per-archive basis using beans.xml.
This behaviour can be changed by providing
an org.jboss.weld.se.archive.isolation
system property with false
value.
After that, each Alternative/Interceptor/Decorator enabled in beans.xml of any archive will be enabled for
the whole SE application.