I am trying to inject a Singleton bean into my Request scoped JAX-RS resource. What I notice is that my Singleton's constructor is invoked on every request, which is obviously not the desired behavior. My Code artifacts are as below:-
JAX-RS Resource
@Path("/thing")
@ManagedBean
public class ThingResource {
//This is desired to be Singleton
@Inject
@RedisThingDb
private ThingDb thingDb;
//This is request scoped
@Inject
private MyRequestScopedObj obj;
@GET
@Path("/{id}")
@Produces("application/json")
public Thing getById(@PathParam("id") String thingId) {
return thingDb.findById(thingId);
}
}
@RedisThingDb Annotation that marks it as a Singleton
@Qualifier
@Singleton
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER })
public @interface RedisThingDb {
}
Producer Code that creates the RedisDb object.
@Produces
@RedisThingDb
public ThingDb getRedisDb() {
return new RedisDb();// This should be called once, because @RedisThingDb is singleton.
}
RedisDb
public class RedisDb implements ThingDb {
public RedisDb() {
logger.debug("Constructing...");
}
public Thing findById(Long id){
...
}
}
Dependency from pom.xml (Implementation is Wildfly container)
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
I am using javax.annotation.ManagedBean (@ManagedBean) annotation to turn the JAX-RS into a CDI managed bean. The @RedisThingDb annotation is marked as @Singleton. The JAX-RS resource is request scoped and has other request scoped beans injected into it.