Jersey 2 + HK2 - @ApplicationScoped not working

I have a class

@ApplicationScoped public class Service{ private Map<String, Integer> something ; private final Logger LOGGER = LoggerFactory.getLogger(Service.class); @PostConstruct public void initialize(){ something = new HashMap<>(); } public void increase(String userName){ something.put(userName, something.getOrDefault(userName, 0) + 1); } public Map<String, Integer> getSomething(){ return this.something; } public Integer getSomethingForUser(String userName){ return something.getOrDefault(userName, 0); } } 

I want to be globally a single instance.

The problem is that when I insert this service in two different places, I have two different instances of the service - which always returns a counter of 0 . .toString() returns the following:

 package.services.Service@492e4f4b package.services.Service@4bc86c4d 

I created this service to test my implementation of the HK2-Jersey, which apparently does not work as it should.

web.xml:

 <servlet-name>jersey-serlvet</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>io.swagger.jaxrs.listing,mypackage.rest</param-value> </init-param> <init-param> <param-name>jersey.config.server.provider.classnames</param-name> <param-value> io.swagger.jaxrs.listing.ApiListingResource, io.swagger.jaxrs.listing.SwaggerSerializers </param-value> </init-param> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>mypackage.config.ApplicationConfiguration</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey-serlvet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> 

ApplicationConfiguration.java:

 public class ApplicationConfiguration extends ResourceConfig { public ApplicationConfiguration() { register(new AbstractBinder() { @Override protected void configure() { bind(Service.class).to(Service.class); } }); packages(true, "com.mypackage.rest"); } 

}

Without this function, bind server throws an exception that @Inject did not execute.

Can someone point out what is wrong?

+1
source share
1 answer

There is no such thing as @ApplicationScoped . This is only a CDI (this is different). HK2 has singleton coverage. With your configuration you can either do

 bind(new Service()).to(Service.class); 

which will automatically make it single. The only problem is that you lose any injection container (if required). Another way is to set the region in the in(Scope) method

 bind(Service.class).to(Service.class).in(Singleton.class); 

This is javax.inject.Singleton .

+1
source

All Articles