如何解决如何在guice模块中注入servlet上下文?
很抱歉输入错误的标题...
免责声明:在网络应用程序方面没有太多经验,主要是使用dropwizard。
所以我一直在尝试在Java Web应用程序中使用guice
我在servlet /资源文件中有servletContext,但是我需要在guice模块中注入,如何在guice模块中注入servlet上下文?
下面是参考代码,不胜感激!
CacheService
public interface CacheService {
public abstract String hello();
}
CacheServiceImpl
public class CacheServiceImpl implements CacheService {
JedisPool jedisPool = null;
@Context
private ServletContext servletContext;
@Provides
public String hello() {
log.info("CacheServiceImpl servletContext {}",servletContext); // this is null
return "hello world";
}
@Provides
public Jedis getJedisConnection() {
HostAndPort redisServer = HostAndPortUtil.getRedisServers().get(0);
if (jedisPool == null)
jedisPool = new JedisPool(getJedisPoolConfig(),redisServer.getHost(),redisServer.getPort(),Protocol.DEFAULT_TIMEOUT,servletContext.getInitParameter("REDIS_PSWD")); // sample example of servletContext requirement,there are other functions in this module which need context
return jedisPool.getResource();
}
}
CacheModule
public class CacheModule implements Module{
public void configure(final Binder binder) {
binder.bind(ResourceServlet.class);
binder.bind(CacheService.class).to(CacheServiceImpl.class);
}
}
ResourceServlet
@Slf4j
@Path("/")
@Singleton
public class ResourceServlet {
@Context
private ServletContext servletContext;
@Inject
public ResourceServlet(CacheService storageModule) throws JAXBException {
log.info("base {}",storageModule.hello());
}
@GET
@Path("/test")
@Produces({MediaType.APPLICATION_JSON})
public Product abc() {
log.info("servletContext {}",servletContext); // this is not null but how do i pass it on to module?
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>resteasy.guice.modules</param-name>
<param-value>com.org.app.guice.CacheModule</param-value>
</context-param>
<listener>
<listener-class>
org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener
</listener-class>
</listener>
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。