我一直在試圖將Spring 4與Jersey 2一起使用,並注意到使用jersey-spring3擴展沒有辦法讓@Named
由Spring管理註釋資源。他們必須註明@Component
由Spring管理。在Jersey 2 + Spring中使用JSR-330註解
如果資源註釋爲@Named
HK2似乎「接管」管理該資源。
資源
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!";
}
}
在以下日誌消息下面Spring的ApplicationContext
<?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>
結果被打印在啓動
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
和一對夫婦的後GET調用。
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]
所以它似乎春天將創建一個豆,但不是用來服務請求的一個多數民衆贊成。但是,如果使用Named
而不是Component
,則整個生命週期由Spring管理。
有沒有辦法使用標準@Named
註釋並確保Spring完全管理資源的生命週期?