我以前从未使用过guice,我想在一个示例项目上试用guice,这个示例项目有一个服务bean支持的基于jersey的JAX。我遵循了这个指南:http://randomizedsort.blogspot.de/2011/05/using-guice-ified-jersey-in-embedded.html,并能够使它开始工作。我的设置非常简单,JAX-RS资源是通过Guice调用的,并且有一个由Guice注释@Inject并注入的字段:
@Path("configuration")
@Produces(MediaType.APPLICATION_JSON)
@Singleton
public class ConfigurationResource {
@Inject
private ConfigurationService configurationService;到目前为止,一切都按其应有的方式工作,除了以下内容:我正在使用GuiceServletContextListener来设置设置,并且必须显式地命名每个组件:
@WebListener
public class GuiceInitializer extends GuiceServletContextListener{
@Override
protected Injector getInjector() {
return Guice.createInjector(new JerseyServletModule() {
@Override
protected void configureServlets() {
//resources
bind(ConfigurationResource.class);
//services
bind(ConfigurationService.class).to(ConfigurationServiceImpl.class);
// Route all requests through GuiceContainer
serve("/management/*").with(GuiceContainer.class);
}
});
}
}我发现显式命名所有依赖项非常不方便。我以前使用过独立的球衣,它完全可以自动扫描定义包中的资源。而且,Spring和CDI能够将实现映射到接口,而无需显式命名它们。
现在问题部分:
提前谢谢。里昂
发布于 2016-05-08 21:48:48
我认为Guice并没有为类似Spring框架的组件扫描这样的东西提供支持。然而,在Guice中模拟这个特性并不困难。
您只需编写一个助手模块,如下所示
import com.google.inject.AbstractModule;
import org.reflections.Reflections;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* To use this helper module, call install(new ComponentScanModule("com.foo", Named.class); in the configure method of
* another module class.
*/
public final class ComponentScanModule extends AbstractModule {
private final String packageName;
private final Set<Class<? extends Annotation>> bindingAnnotations;
@SafeVarargs
public ComponentScanModule(String packageName, final Class<? extends Annotation>... bindingAnnotations) {
this.packageName = packageName;
this.bindingAnnotations = new HashSet<>(Arrays.asList(bindingAnnotations));
}
@Override
public void configure() {
Reflections packageReflections = new Reflections(packageName);
bindingAnnotations.stream()
.map(packageReflections::getTypesAnnotatedWith)
.flatMap(Set::stream)
.forEach(this::bind);
}
}若要组件扫描包(如com.foo )和子包中包含@Singleton的类,请以下列方式使用:
public class AppModule extends AbstractModule {
public void configure() {
install(new ComponentScanModule("com.foo", Singleton.class));
}
}https://stackoverflow.com/questions/30313403
复制相似问题