I have implemented a Jersey REST service and want to add dependency injection. However, even after trying many different suggestions across the web, I cannot get past the following error:
SEVERE: Servlet.service() for servlet [com.example.iam2tc.api.JAXRSApplication] in context with path [/app] threw exception [A MultiException has 3 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=UserDAO,parent=UserAPI,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1100911426)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.example.iam2tc.api.UserAPI errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on com.example.iam2tc.api.UserAPI
] with root cause
org.glassfish.hk2.api.UnsatisfiedDependencyException:
There was no object available for injection at SystemInjecteeImpl(requiredType=UserDAO,parent=UserAPI,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1100911426)
My endpoint class where I want to inject the DAO class looks like this:
@RequestScoped
@Path("/userAPI")
public class UserAPI {
private static final Logger logger = Logger.getLogger(UserAPI.class.getName());
@Inject
private UserDAO userDAO;
@GET
public Response getUsers() {
logger.info("getUsers()");
}
}
The DAO that I want to inject looks like this:
@ApplicationScoped
public class UserDAO {
private static final Logger logger = Logger.getLogger(UserDAO.class.getName());
}
I added the following dependencies to my build.gradle file:
// JAXRS Interfaces
implementation group: 'javax.ws.rs', name: 'javax.ws.rs-api', version: '2.1.1'
// Dependencies for Jersey REST API
implementation 'org.glassfish.jersey.core:jersey-server:2.41'
implementation 'org.glassfish.jersey.media:jersey-media-json-jackson:2.41'
implementation 'org.glassfish.jersey.containers:jersey-container-servlet:2.41'
implementation group: 'org.glassfish.jersey.inject', name: 'jersey-hk2', version: '2.41'
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.14.0'
compileOnly group: 'org.glassfish.jersey.containers.glassfish', name: 'jersey-gf-cdi', version: '2.14'
I also tried adding a beans.xml
file to both WEB-INF
and META-INF
folders:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
bean-discovery-mode="all">
</beans>
But many answers (#1, #2) here suggest that it should be possible without specifying a beans.xml or Binder at all.
What am I missing here in order to get this to work?