CDI failure with Dependent/applicatio Scope class - dependency-injection

I am trying to Inject ServletContext in my dependant scope class but it always gives the failure.
java.lang.IllegalStateException: No CXF message usable for JAX-RS #Context injections in that thread so can't use interface javax.servlet.ServletContext
I am not able to undestand the reason that why can't I inject it here. I am using a producer method and when inside producer method,I try to access ServletContext obj then it gives above exception. I have also checked if the Injected servlet context is null but it is not null. But When I call any method using it for example sc.getContextPath() it gives the above exception. Below is the code snippet:
#Dependent
public class AuthContexthandler {
#Context
ServletContext sc;
#Produces
JWTAuthContextInfo getInfo() {
try{
System.out.println(sc.getContextPath()); //here I get the above mentioned error
//rest of the code
}catch(Exception e){
e.printStackTrace();
}
}
}

you must use #inject instead of #Context.
you can use #Context to inject object instances related to the context of HTTP requests into to JAX-RS source class and as AuthContextHandler(as #Christoph Böhme said) is not a JAX-RS source class so you cannot use #Context
but as http://docs.jboss.org/weld/reference/latest/en-US/html_single/ says:
An object bound to a lifecycle context is called a bean. CDI includes
built-in support for several different kinds of bean, including the
following Java EE component types:
managed beans, and EJB session beans. Both managed beans and EJB
session beans may inject other beans. But some other objects, which
are not themselves beans in the sense used here, may also have beans
injected via CDI. In the Java EE platform, the following kinds of
component may have beans injected:
message-driven beans,
interceptors,
servlets,
servlet filters and
servlet event listeners,
JAX-WS service endpoints and handlers,
JAX-RS resources,
providers and javax.ws.rs.core.Application subclasses, and
JSP tag handlers and tag library event listeners.
it means you also can use #Inject annotation in your JAX-RS source class.
there are also some predefined Beans in CDI such as ServletContext that you can use #inject annotation to inject them.
https://docs.jboss.org/seam/3/servlet/latest/reference/en-US/html/injectablerefs.html
https://docs.oracle.com/javaee/7/tutorial/cdi-adv004.htm

Related

Grails-The different dependence Injection ways in grails

What's the difference of different way to inject dependence in grails:
ABCService abcService
def abcService
#Autowired
ABCService ABCService
Expected type is specified, if service with name abcService (or other Spring bean with such name) will have different class, then you'll get ClassCastException here
Just any bean with name abcService
Spring annotation, it's optional. But if you've marked a field but Grails/Spring cannot find such bean it will throw NoSuchBeanDefinitionException (previous two will get null if it doesn't exists) #Autowired could be combined with def type also
Basically Grails services are standard Spring beans, Grails just follows convention over configuration that for every class in services dir it will create a bean with name abcService that could be autowired into other beans. All other job is done by Spring. See also docs for Spring and Grails

Inject singleton bean into session bean via remote interface, object always "null"

I need to inject a singleton bean into the session bean. Below are the corresponding classes. The problem is that the injected object is always null. I tried all of the JNDI lookup strings which my JBoss 7.0.1 server showed me during startup (i.e. JNDI bindings for session bean named GlobalBean in deployment unit subdeployment .. of deployment .. are as follows: ..). I also tried commenting out the #EJB annotation in GlobalBean.java and also tried to use the "ejb/GlobalBean" during injection. However, no luck. What could be the reason? Thx.
GlobalBean.java:
#Startup
#Singleton
#Remote(GlobalBeanRemote.class)
#EJB(name="ejb/GlobalBean", beanName="GlobalBean", beanInterface=GlobalBeanRemote.class)
#ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class GlobalBean implements GlobalBeanRemote
{
// CODE
}
SessionBean.java:
#Stateful
public class SessionBean extends ParentBean
{
#EJB(name="java:module/GlobalBean!project.framework.interfaces.GlobalBeanRemote")
private GlobalBeanRemote globalBeanAPI3;
// CODE
}
In your SessionBean class try changing name attribute of #EJB to mappedName.
#EJB(mappedName="java:module/GlobalBean!project.framework.interfaces.GlobalBeanRemote")
This will, of course, only work if your two beans are in the same module.
Update
Given that your beans are in separate modules, try using the java:app namespace:
#EJB(mappedName="java:app ...")
The java:app namespace is used to look up local enterprise beans packaged within the same application. That is, the enterprise bean is packaged within an EAR file containing multiple Java EE modules. JNDI addresses using the java:app namespace are of the following form:
java:app[/module name]/enterprise bean name[/interface name]
Also try removing GlobalBean's #EJB annotation. #EJB is used to define a dependency.

JSF Serialization/Deserialization

We use JSF within our presentation layer. Most classes looks like this:
#Named
#SessionScoped
public class MyHandler implements Serializable {
#Inject
private MyHelper helper;
#EJB
private transient MyFacade myFacade;
...
}
In general an JSF handler has one transient reference to an facade. The facade connects the presentation layer with our service layer. Helper classes will almost be injected through cdi.
JSF serializes the state of an handler but what happens on deserialization? Are the references automagically be restored? How could I check this or tell JSF to serialize/deserialize an managed jsf bean(testing)?
As per spec all (relevant) CDI-managed dependencies are proxied and the proxies are required to be passivable, so there is no problem with de-/serialization :)
[...] Finally, client proxies may be passivated [...]

Why does the #PostConstruct method not get called using BeanManager.getReference() to obtain an instance?

We are currently moving from JSF-ManagedBeans to CDI. Unfortunately we have made excessive use of the EL-Resolver in the past in order to gain static access to session scoped beans managed by JSF.
Since CDI dependency injection is not available everywhere I rewrote the existing static lookup to make use of the BeanManager (Using SEAM-Solder extending BeanManagerAware).
Iterator<Bean<?>> iterator = beans.iterator();
Bean<T> bean = (Bean<T>) iterator.next(); // possible NPE, I know :)
CreationalContext<T> creationalContext = beanManager.createCreationalContext(bean);
T contextual = (T) beanManager.getReference(bean, type, creationalContext);
return contextual;
The code works and returns a container managed instance of the desired bean. BUT: the methods annotated with #PostConstruct do not get called using getReference(). Perhaps you guys know how to do it. Couldn't find anything googling the issue :-/
Best regards!
You should be using Application#evaluateExpressionGet() for this. Not only for CDI beans, but actually also for JSF beans you previously had.
FacesContext context = FacesContext.getCurrentInstance();
Bean bean = (Bean) context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);
// ...
Much cleaner, however, is to just use CDI's #Inject or JSF's #ManagedProperty instead.
See also:
Get JSF managed bean by name in any Servlet related class

Is there any Spring #Required annotation equivalent in EJB 3.0?

Is there any equivalent annotation in EJB for #Required (Spring)? I do dependency injection using setters and I want to be sure that resource was injected (almost no probability of NullPointerException ;)). In Spring it is easy:
#Required
public void setProperty(Property p) {
this.property = p;
}
Is there any way to do such a validation in EJB? (Maybe some other solution than annotatations). Thanks
In ejb injection is done via #EJB and #Resource (as stated above).
If the bean for the given (or auto-generated) name doesn't exist you get an error from the container (in many cases this happens at deployment time).
The only way to (maybe) get a nullpointer exception inside a ejb bean is if you try to access an injected object in the default constructor. By spec injection happens after the constructor and before the #PostConstruct lifecycle is called.

Resources