J'ai essayé d'utiliser Spring 4 avec Jersey 2 et je remarque que l'utilisation de l'extension jersey-spring3 ne permet pas de faire des ressources annotées @Named
gérées par Spring. Ils doivent être annotés avec @Component
pour être gérés par Spring.Utilisation des annotations JSR-330 avec Jersey 2 + Spring
Si une ressource est annotée avec @Named
, HK2 semble "prendre en charge" la gestion de cette ressource.
ressources
import com.example.jersey.spring.Greeting;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Named
@Singleton
@Path("resource")
public class Resource {
private static final Logger logger = Logger.getLogger("Resource");
public void init() {
logger.info("Creating -> " + this + " injected with -> " + greeting);
}
@Inject
private Greeting greeting;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getIt() {
logger.info("Working on " + this + " Greeting " + greeting);
return "Got it!";
}
}
avec le ressort applicationContext suivantes
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
default-init-method="init">
<context:component-scan base-package="com.example.jersey.webapp"/>
<bean id="greeting" class="com.example.jersey.spring.Greeting"/>
</beans>
Résultats dans les messages journaux suivants en cours d'impression au démarrage
Oct 18, 2017 3:11:44 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Oct 18, 2017 3:11:44 PM com.example.jersey.webapp.Resource init
INFO: Creating -> [email protected] injected with -> [email protected]
Oct 18, 2017 3:11:45 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 249 ms
Et après quelques GET appels.
Oct 18, 2017 3:11:56 PM com.example.jersey.webapp.Resource getIt
INFO: Working on [email protected] Greeting [email protected]
Oct 18, 2017 3:12:03 PM com.example.jersey.webapp.Resource getIt
INFO: Working on [email protected] Greeting [email protected]
Il semble donc que Spring crée le bean mais ce n'est pas celui qui est utilisé pour répondre aux demandes. Cependant, si au lieu de Named
, Component
est utilisé, le cycle de vie entier est géré par Spring.
Existe-t-il un moyen d'utiliser l'annotation @Named
standard et de s'assurer que Spring gère complètement le cycle de vie de la ressource?