Reputation: 3336
I'm creating a JAR that can be use by WEB or DESKTOP application. This JAR should have some classes with @RequestScoped and others CDI annotations, so i have some doubts about it:
1) I understand that @RequestScoped is just for HTTP REQUEST, but how can i use this in a Desktop Application ? It's possible ? 2) I'm using this dependency:
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet</artifactId>
<version>2.4.1.Final</version>
</dependency>
But this dependency is just for weld for WEB, i need some more generic that should work in WEB or DESKTOP.
If i use "weld-se" as dependency my JAR wil work only for DESKTOP, i don't want to this.
Upvotes: 1
Views: 2540
Reputation: 6753
As was said by user MouseEvent in the comment, it is usually better to have two separate JARs for this.
However, what I aim to answer is your question about @RequestScoped
beans in non-web environment (and also @Session
and @Application
). So let's say we are using Weld in SE environment - now, what works and what doesn't?
@ApplicationScoped
works just fine and as you would expect. One bean per application. It's lifecycle starts when you boot container and stops when you shut it down. An alternative to this is usage of @javax.inject.Singleton
(note that this is CDI singleton, not EJB) beans, but that should be limited to SE only - this behaves equally to application scoped bean but has no proxy created. This might give you the upper hand in some cases but also prevents things like serialization.
@SessionScoped
at the moment does not work in SE environment as it does not really make any sense there. As you said yourself, you have no session there.
@RequestScoped
does work in SE. This makes sense as "request" can mean more things than just plain old HTTP request. However, you will need to take care of activation of this scope. While there are several ways (such as extending the context and handling activation yourself) I would advise to use an annotation (interceptor binding in fact) provided in Weld API - @ActivateRequestContext
. You simply put the annotation on top of your method and Weld will activate the request context before the method starts and shut it down afterwards. You can also put this on whole class which means it will work for every method. Note that you will need have dependency on Weld API to gain access to this annotation (or you need to use CDI 2.0 where this was added as well).
As for your dependency, in SE environment, you will want this one:
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se</artifactId>
<version>2.4.1.Final</version>
</dependency>
Upvotes: 3