Jersey 2 + HK2 - @ApplicationScoped not working

2019-08-15 18:10发布

问题:

I have 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);
 }
}

Which I want to be globally one instance.

The problem is, that when I'm injecting this service in two different places, I have two different instances of the service - which causes to return always counter 0. .toString() returns as follows:

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

I created this service to test my HK2-Jersey implementation, which is apparently not working as 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 bind function, server throws exception that @Inject wasn't satisfied.

Can anybody point out, what is wrong?

回答1:

There's no such thing as @ApplicationScoped in HK2. That is only CDI (which is different). In HK2 there's a singleton scope. With your configuration, you can either do

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

which will automatically make it a singleton. Only problem with this is that you lose any injection by the container (if you require any). The other way is to set the scope in the in(Scope) method

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

That's javax.inject.Singleton.