how to use guice correctly for dependency inject in java servlets?

530 Views Asked by At

sorry for the bad question title...
Disclaimer: Not much experience around web-apps, primarily used dropwizard.

So i have been trying to use guice in my java web-app
Initially without guice, servlets were serving the api correctly but after configuring servlet to be served from guice for below endpoint,

http://localhost:8080/myServlets/test

I am getting below error:

HTTP Status 404 – Not Found Type Status Report

Message The requested resource [/myServlets/test] is not available

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

Apache Tomcat/8.5.57

with below stacktrace:

16-Sep-2020 11:33:43.941 INFO [AsyncFileHandlerWriter-2008362258] org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading Illegal access: this web application instance has been stopped already. Could not load [com.google.inject.internal.util.LineNumbers$LineNumberReader]. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
    java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load [com.google.inject.internal.util.LineNumbers$LineNumberReader]. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
        at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading(WebappClassLoaderBase.java:1378)
        at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForClassLoading(WebappClassLoaderBase.java:1366)
        at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1218)
        at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1180)
        at com.google.inject.internal.util.StackTraceElements$1.load(StackTraceElements.java:49)
        at com.google.inject.internal.util.StackTraceElements$1.load(StackTraceElements.java:45)
        at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3529)
        at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2278)
        at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2155)
        at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2045)
        at com.google.common.cache.LocalCache.get(LocalCache.java:3953)
        at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3976)
        at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4960)
        at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4966)
        at com.google.inject.internal.util.StackTraceElements.forMember(StackTraceElements.java:71)
        at com.google.inject.internal.Messages.formatParameter(Messages.java:286)
        at com.google.inject.internal.Messages.formatInjectionPoint(Messages.java:273)
        at com.google.inject.internal.Messages.formatSource(Messages.java:229)
        at com.google.inject.internal.Messages.formatSource(Messages.java:220)
        at com.google.inject.internal.Messages.formatMessages(Messages.java:90)
        at com.google.inject.ConfigurationException.getMessage(ConfigurationException.java:73)
        at java.base/java.lang.Throwable.getLocalizedMessage(Throwable.java:396)
        at java.base/java.lang.Throwable.toString(Throwable.java:485)
        at java.base/java.lang.String.valueOf(String.java:2951)
        at java.base/java.io.PrintWriter.println(PrintWriter.java:837)
        at org.apache.juli.OneLineFormatter$IndentingPrintWriter.println(OneLineFormatter.java:298)
        at java.base/java.lang.Throwable$WrappedPrintWriter.println(Throwable.java:768)
        at java.base/java.lang.Throwable.printStackTrace(Throwable.java:659)
        at java.base/java.lang.Throwable.printStackTrace(Throwable.java:725)
        at org.apache.juli.OneLineFormatter.format(OneLineFormatter.java:171)
        at org.apache.juli.FileHandler.publish(FileHandler.java:291)
        at org.apache.juli.AsyncFileHandler.publishInternal(AsyncFileHandler.java:146)
        at org.apache.juli.AsyncFileHandler$LogEntry.flush(AsyncFileHandler.java:185)
        at org.apache.juli.AsyncFileHandler$LoggerThread.run(AsyncFileHandler.java:161)

Tried Guice Git but createInjector part stumps me as there is no main method.

Reference code is below, any help is appreciated!

CacheService

public interface CacheService {
    public abstract String hello();
}

CacheServiceImpl

import com.google.inject.Provides;

public class CacheServiceImpl implements CacheService {

    @Provides
    public String hello() {
        return "hello world";
    }
}

CacheModule

import com.google.inject.AbstractModule;

public class CacheModule extends AbstractModule {

    protected void configure() {
        bind(CacheService.class).to(CacheServiceImpl.class);
    }
}

MyGuiceServletConfig

public class MyGuiceServletConfig extends GuiceServletContextListener {
    @Override
    protected Injector getInjector() {
        return Guice.createInjector(new ServletModule() {
            @Override
            protected void configureServlets() {
                serve("/*").with(ResourceServlet.class);
                bind(CacheModule.class);
            }
        });
    }
}

ResourceServlet

@Slf4j
@Path("/")
@Singleton
public class ResourceServlet extends HttpServlet {

    @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);
        
    }
}

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">
    <display-name>myServlets</display-name>
    <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>

    <!-- Inject Guice -->
    <filter>
        <filter-name>guiceFilter</filter-name>
        <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>guiceFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>com.myorg.application.guice.MyGuiceServletConfig</listener-class>
    </listener>
</web-app>
0

There are 0 best solutions below