Yes, @Inject
can act as @Autowired
... given some conditions.
Guice doesn't require Module
s, though they're very often used. So you can get rid of them if you want to.
If your class is a concrete class, you can directly @Inject
it, just like @Autowired
, but you also probably have to mark the class @Singleton
because the default scope in Guice is not singleton, but a new instance everyone, unlike Spring.
Guice is not Spring, but the most important features of one are present in the other.
Using Guice with Tomcat
When you want to use Guice with Tomcat, there is very little configuration to do, but there is still configuration. You will require a Module
, but only the servlet.
In your web.xml
, add the following:
<listener>
<listener-class>path.to.MyGuiceServletConfig</listener-class>
</listener>
<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>
MyGuiceServletConfig.java
public class MyGuiceServletConfig extends GuiceServletContextListener {
@Override protected Injector getInjector() {
return Guice.createInjector(new ServletModule() {
@Override protected void configureServlets() {
serve("/*").with(MyServlet.class); // Nothing else is needed.
}
});
}
}
MyServlet.java
public class MyServlet extends HttpServlet {
@Inject // Similar to @Autowired
private MyService myService;
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
resp.getWriter().write(myService.hello("Guice"));
}
}
Now you have a choice with MyService
: either you make an interface out of it and you have to define, and bind an implementation, or you make a concrete class out of it.
MyService
as an interface
MyService.java
@ImplementedBy(MyServiceImpl.class) // This says "hey Guice, the default implementation is MyServiceImpl."
public interface MyService {
String hello(String name);
}
MyServiceImpl.java
@Singleton // Use the same default scope as Spring
public class MyServiceImpl implements MyService {
// @Inject dependencies as you wish.
public String hello(String name) { return "Hello, " + name + "!"; }
}
If you want to avoid the @ImplementedBy
, you can still use your module above, and add bind(MyService.class).to(MyServiceImpl.class).in(Scopes.SINGLETON);
, or write a provider method in the same Module
:
@Provides @Singleton MyService provideMyService() {
return new MyServiceImpl();
}
MyService
as a concrete class
MyService.java
@Singleton // Use the same default scope as Spring
public class MyService {
// @Inject dependencies as you wish.
public String hello(String name) { return "Hello, " + name + "!"; }
}