Apply and enforce spring-javaformat
This commit is contained in:
committed by
Dave Syer
parent
ad60397400
commit
7254dc8be7
1
.springjavaformatconfig
Normal file
1
.springjavaformatconfig
Normal file
@@ -0,0 +1 @@
|
||||
java-baseline=8
|
||||
14
pom.xml
14
pom.xml
@@ -117,6 +117,20 @@
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>io.spring.javaformat</groupId>
|
||||
<artifactId>spring-javaformat-maven-plugin</artifactId>
|
||||
<version>0.0.31</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>validate</phase>
|
||||
<inherited>true</inherited>
|
||||
<goals>
|
||||
<goal>validate</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
@@ -22,17 +22,19 @@ import com.google.inject.Key;
|
||||
|
||||
/**
|
||||
* Convenience class used to map a Guice {@link Provider} to a Spring bean.
|
||||
*
|
||||
*
|
||||
* @author Dave Syer
|
||||
*/
|
||||
class GuiceFactoryBean<T> implements FactoryBean<T> {
|
||||
|
||||
private final Key<T> key;
|
||||
|
||||
private final Class<T> beanType;
|
||||
|
||||
private final boolean isSingleton;
|
||||
|
||||
|
||||
@Autowired
|
||||
private Injector injector;
|
||||
|
||||
|
||||
public GuiceFactoryBean(Class<T> beanType, Key<T> key, boolean isSingleton) {
|
||||
this.beanType = beanType;
|
||||
@@ -54,4 +56,5 @@ class GuiceFactoryBean<T> implements FactoryBean<T> {
|
||||
public boolean isSingleton() {
|
||||
return this.isSingleton;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -30,9 +30,9 @@ import org.springframework.guice.module.SpringModule;
|
||||
* class (and if added to many then the filters are combined with logical OR). By default
|
||||
* all beans in the context will be bound to Guice with all of their implemented
|
||||
* interfaces. If you need to filter out which beans are added you can filter by class.
|
||||
*
|
||||
*
|
||||
* @author Dave Syer
|
||||
*
|
||||
*
|
||||
* @see SpringModule
|
||||
* @see GuiceModuleMetadata
|
||||
*
|
||||
@@ -45,42 +45,39 @@ public @interface GuiceModule {
|
||||
|
||||
/**
|
||||
* Specifies which types are eligible for inclusion in Guice module
|
||||
*
|
||||
* @return filters for inclusion
|
||||
*/
|
||||
Filter[] includeFilters() default {};
|
||||
|
||||
/**
|
||||
* Specifies which types are not eligible for inclusion in Guice module.
|
||||
*
|
||||
* @return filters for exclusion
|
||||
*/
|
||||
Filter[] excludeFilters() default {};
|
||||
|
||||
/**
|
||||
* Specifies which names (by regex) are eligible for inclusion in Guice module
|
||||
*
|
||||
* @return regexes
|
||||
*/
|
||||
String[] includePatterns() default {};
|
||||
|
||||
/**
|
||||
* Specifies which bean names (by regex) are not eligible for inclusion in Guice module.
|
||||
*
|
||||
* Specifies which bean names (by regex) are not eligible for inclusion in Guice
|
||||
* module.
|
||||
* @return regexes
|
||||
*/
|
||||
String[] excludePatterns() default {};
|
||||
|
||||
/**
|
||||
* Specifies which names (by simple wildcard match) are eligible for inclusion in Guice module
|
||||
*
|
||||
* Specifies which names (by simple wildcard match) are eligible for inclusion in
|
||||
* Guice module
|
||||
* @return bean names
|
||||
*/
|
||||
String[] includeNames() default {};
|
||||
|
||||
/**
|
||||
* Specifies which bean names (by simple wildcard match) are not eligible for inclusion in Guice module.
|
||||
*
|
||||
* Specifies which bean names (by simple wildcard match) are not eligible for
|
||||
* inclusion in Guice module.
|
||||
* @return bean names
|
||||
*/
|
||||
String[] excludeNames() default {};
|
||||
|
||||
@@ -47,12 +47,11 @@ import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Registers bean definitions for Guice modules.
|
||||
*
|
||||
*
|
||||
* @author Dave Syer
|
||||
*
|
||||
*/
|
||||
class GuiceModuleRegistrar implements ImportBeanDefinitionRegistrar,
|
||||
ResourceLoaderAware {
|
||||
class GuiceModuleRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {
|
||||
|
||||
private ResourceLoader resourceLoader = new DefaultResourceLoader();
|
||||
|
||||
@@ -62,30 +61,20 @@ class GuiceModuleRegistrar implements ImportBeanDefinitionRegistrar,
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerBeanDefinitions(AnnotationMetadata annotation,
|
||||
BeanDefinitionRegistry registry) {
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder
|
||||
.genericBeanDefinition(GuiceModuleMetadataFactory.class);
|
||||
builder.addPropertyValue("includeFilters",
|
||||
parseFilters(annotation, "includeFilters"));
|
||||
builder.addPropertyValue("excludeFilters",
|
||||
parseFilters(annotation, "excludeFilters"));
|
||||
builder.addPropertyValue("includePatterns",
|
||||
parsePatterns(annotation, "includePatterns"));
|
||||
builder.addPropertyValue("excludePatterns",
|
||||
parsePatterns(annotation, "excludePatterns"));
|
||||
builder.addPropertyValue("includeNames",
|
||||
parseNames(annotation, "includeNames"));
|
||||
builder.addPropertyValue("excludeNames",
|
||||
parseNames(annotation, "excludeNames"));
|
||||
public void registerBeanDefinitions(AnnotationMetadata annotation, BeanDefinitionRegistry registry) {
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(GuiceModuleMetadataFactory.class);
|
||||
builder.addPropertyValue("includeFilters", parseFilters(annotation, "includeFilters"));
|
||||
builder.addPropertyValue("excludeFilters", parseFilters(annotation, "excludeFilters"));
|
||||
builder.addPropertyValue("includePatterns", parsePatterns(annotation, "includePatterns"));
|
||||
builder.addPropertyValue("excludePatterns", parsePatterns(annotation, "excludePatterns"));
|
||||
builder.addPropertyValue("includeNames", parseNames(annotation, "includeNames"));
|
||||
builder.addPropertyValue("excludeNames", parseNames(annotation, "excludeNames"));
|
||||
AbstractBeanDefinition definition = builder.getBeanDefinition();
|
||||
String name = new DefaultBeanNameGenerator().generateBeanName(definition,
|
||||
registry);
|
||||
String name = new DefaultBeanNameGenerator().generateBeanName(definition, registry);
|
||||
registry.registerBeanDefinition(name, definition);
|
||||
}
|
||||
|
||||
protected static class GuiceModuleMetadataFactory implements
|
||||
FactoryBean<GuiceModuleMetadata> {
|
||||
protected static class GuiceModuleMetadataFactory implements FactoryBean<GuiceModuleMetadata> {
|
||||
|
||||
private Collection<? extends TypeFilter> includeFilters;
|
||||
|
||||
@@ -125,19 +114,12 @@ class GuiceModuleRegistrar implements ImportBeanDefinitionRegistrar,
|
||||
|
||||
@Override
|
||||
public GuiceModuleMetadata getObject() throws Exception {
|
||||
return new GuiceModuleMetadata()
|
||||
.include(
|
||||
includeFilters.toArray(new TypeFilter[includeFilters.size()]))
|
||||
.exclude(
|
||||
excludeFilters.toArray(new TypeFilter[excludeFilters.size()]))
|
||||
.include(
|
||||
includePatterns.toArray(new Pattern[includePatterns.size()]))
|
||||
.exclude(
|
||||
excludePatterns.toArray(new Pattern[excludePatterns.size()]))
|
||||
.include(
|
||||
includeNames.toArray(new String[includeNames.size()]))
|
||||
.exclude(
|
||||
excludeNames.toArray(new String[excludeNames.size()]));
|
||||
return new GuiceModuleMetadata().include(includeFilters.toArray(new TypeFilter[includeFilters.size()]))
|
||||
.exclude(excludeFilters.toArray(new TypeFilter[excludeFilters.size()]))
|
||||
.include(includePatterns.toArray(new Pattern[includePatterns.size()]))
|
||||
.exclude(excludePatterns.toArray(new Pattern[excludePatterns.size()]))
|
||||
.include(includeNames.toArray(new String[includeNames.size()]))
|
||||
.exclude(excludeNames.toArray(new String[excludeNames.size()]));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -178,8 +160,7 @@ class GuiceModuleRegistrar implements ImportBeanDefinitionRegistrar,
|
||||
return result;
|
||||
}
|
||||
|
||||
private Set<TypeFilter> parseFilters(AnnotationMetadata annotation,
|
||||
String attributeName) {
|
||||
private Set<TypeFilter> parseFilters(AnnotationMetadata annotation, String attributeName) {
|
||||
|
||||
Set<TypeFilter> result = new HashSet<TypeFilter>();
|
||||
AnnotationAttributes attributes = new AnnotationAttributes(
|
||||
@@ -202,8 +183,7 @@ class GuiceModuleRegistrar implements ImportBeanDefinitionRegistrar,
|
||||
switch (filterType) {
|
||||
case ANNOTATION:
|
||||
Assert.isAssignable(Annotation.class, filterClass,
|
||||
"An error occured when processing a @ComponentScan "
|
||||
+ "ANNOTATION type filter: ");
|
||||
"An error occured when processing a @ComponentScan " + "ANNOTATION type filter: ");
|
||||
@SuppressWarnings("unchecked")
|
||||
Class<Annotation> annoClass = (Class<Annotation>) filterClass;
|
||||
typeFilters.add(new AnnotationTypeFilter(annoClass));
|
||||
@@ -213,10 +193,8 @@ class GuiceModuleRegistrar implements ImportBeanDefinitionRegistrar,
|
||||
break;
|
||||
case CUSTOM:
|
||||
Assert.isAssignable(TypeFilter.class, filterClass,
|
||||
"An error occured when processing a @ComponentScan "
|
||||
+ "CUSTOM type filter: ");
|
||||
typeFilters
|
||||
.add(BeanUtils.instantiateClass(filterClass, TypeFilter.class));
|
||||
"An error occured when processing a @ComponentScan " + "CUSTOM type filter: ");
|
||||
typeFilters.add(BeanUtils.instantiateClass(filterClass, TypeFilter.class));
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("Unknown filter type " + filterType);
|
||||
@@ -229,10 +207,11 @@ class GuiceModuleRegistrar implements ImportBeanDefinitionRegistrar,
|
||||
|
||||
if ("REGEX".equals(rawName)) {
|
||||
typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(expression)));
|
||||
} else if ("ASPECTJ".equals(rawName)) {
|
||||
typeFilters.add(new AspectJTypeFilter(expression, this.resourceLoader
|
||||
.getClassLoader()));
|
||||
} else {
|
||||
}
|
||||
else if ("ASPECTJ".equals(rawName)) {
|
||||
typeFilters.add(new AspectJTypeFilter(expression, this.resourceLoader.getClassLoader()));
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Unknown filter type " + filterType);
|
||||
}
|
||||
}
|
||||
@@ -244,7 +223,8 @@ class GuiceModuleRegistrar implements ImportBeanDefinitionRegistrar,
|
||||
|
||||
try {
|
||||
return filterAttributes.getStringArray("pattern");
|
||||
} catch (IllegalArgumentException o_O) {
|
||||
}
|
||||
catch (IllegalArgumentException o_O) {
|
||||
return new String[0];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,11 +6,11 @@ import com.google.inject.Injector;
|
||||
import com.google.inject.Module;
|
||||
|
||||
/***
|
||||
* Factory which allows for custom creation of the Guice Injector to be used
|
||||
* in the @{@link EnableGuiceModules} feature.
|
||||
* Factory which allows for custom creation of the Guice Injector to be used in
|
||||
* the @{@link EnableGuiceModules} feature.
|
||||
*/
|
||||
public interface InjectorFactory {
|
||||
|
||||
public Injector createInjector(List<Module> modules);
|
||||
|
||||
public Injector createInjector(List<Module> modules);
|
||||
|
||||
}
|
||||
|
||||
@@ -73,12 +73,15 @@ import java.util.stream.Collectors;
|
||||
class ModuleRegistryConfiguration implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware {
|
||||
|
||||
private static final String SPRING_GUICE_DEDUPE_BINDINGS_PROPERTY_NAME = "spring.guice.dedup";
|
||||
|
||||
private static final String SPRING_GUICE_AUTOWIRE_JIT_PROPERTY_NAME = "spring.guice.autowireJIT";
|
||||
|
||||
private static final String SPRING_GUICE_STAGE_PROPERTY_NAME = "spring.guice.stage";
|
||||
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
private boolean enableJustInTimeBinding = true;
|
||||
|
||||
@Override
|
||||
@@ -90,13 +93,13 @@ class ModuleRegistryConfiguration implements BeanDefinitionRegistryPostProcessor
|
||||
|
||||
@Override
|
||||
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
|
||||
List<Module> modules = new ArrayList<>(((ConfigurableListableBeanFactory) registry)
|
||||
.getBeansOfType(Module.class).values());
|
||||
List<Module> modules = new ArrayList<>(
|
||||
((ConfigurableListableBeanFactory) registry).getBeansOfType(Module.class).values());
|
||||
modules.add(new SpringModule((ConfigurableListableBeanFactory) registry, enableJustInTimeBinding));
|
||||
Map<Key<?>, Binding<?>> bindings = new HashMap<Key<?>, Binding<?>>();
|
||||
List<Element> elements = Elements.getElements(Stage.TOOL, modules);
|
||||
if (applicationContext.getEnvironment().getProperty(
|
||||
SPRING_GUICE_DEDUPE_BINDINGS_PROPERTY_NAME, Boolean.class, false)) {
|
||||
if (applicationContext.getEnvironment().getProperty(SPRING_GUICE_DEDUPE_BINDINGS_PROPERTY_NAME, Boolean.class,
|
||||
false)) {
|
||||
elements = removeDuplicates(elements);
|
||||
modules = Collections.singletonList(Elements.getModule(elements));
|
||||
}
|
||||
@@ -132,17 +135,16 @@ class ModuleRegistryConfiguration implements BeanDefinitionRegistryPostProcessor
|
||||
}
|
||||
|
||||
private void mapBindings(Map<Key<?>, Binding<?>> bindings, BeanDefinitionRegistry registry) {
|
||||
Stage stage = applicationContext.getEnvironment().getProperty(SPRING_GUICE_STAGE_PROPERTY_NAME, Stage.class, Stage.PRODUCTION);
|
||||
Stage stage = applicationContext.getEnvironment().getProperty(SPRING_GUICE_STAGE_PROPERTY_NAME, Stage.class,
|
||||
Stage.PRODUCTION);
|
||||
boolean ifLazyInit = stage.equals(Stage.DEVELOPMENT);
|
||||
for (Entry<Key<?>, Binding<?>> entry : bindings.entrySet()) {
|
||||
if (entry.getKey().getTypeLiteral().getRawType().equals(Injector.class)
|
||||
|| SpringModule.SPRING_GUICE_SOURCE
|
||||
if (entry.getKey().getTypeLiteral().getRawType().equals(Injector.class) || SpringModule.SPRING_GUICE_SOURCE
|
||||
.equals(Optional.ofNullable(entry.getValue().getSource()).map(Object::toString).orElse(""))) {
|
||||
continue;
|
||||
}
|
||||
if (entry.getKey().getAnnotationType() != null &&
|
||||
entry.getKey().getAnnotationType().getName()
|
||||
.startsWith("com.google.inject.multibindings")) {
|
||||
if (entry.getKey().getAnnotationType() != null
|
||||
&& entry.getKey().getAnnotationType().getName().startsWith("com.google.inject.multibindings")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -157,21 +159,20 @@ class ModuleRegistryConfiguration implements BeanDefinitionRegistryPostProcessor
|
||||
args.addIndexedArgumentValue(2, Scopes.isSingleton(binding));
|
||||
bean.setConstructorArgumentValues(args);
|
||||
bean.setTargetType(ResolvableType.forType(key.getTypeLiteral().getType()));
|
||||
if(!Scopes.isSingleton(binding)) {
|
||||
if (!Scopes.isSingleton(binding)) {
|
||||
bean.setScope(ConfigurableBeanFactory.SCOPE_PROTOTYPE);
|
||||
}
|
||||
if (source instanceof ElementSource) {
|
||||
bean.setResourceDescription(
|
||||
((ElementSource) source).getDeclaringSource().toString());
|
||||
bean.setResourceDescription(((ElementSource) source).getDeclaringSource().toString());
|
||||
}
|
||||
else {
|
||||
bean.setResourceDescription(SpringModule.SPRING_GUICE_SOURCE);
|
||||
}
|
||||
bean.setAttribute(SpringModule.SPRING_GUICE_SOURCE, true);
|
||||
if (key.getAnnotationType() != null) {
|
||||
bean.addQualifier(new AutowireCandidateQualifier(Qualifier.class,
|
||||
getValueAttributeForNamed(key)));
|
||||
bean.addQualifier(new AutowireCandidateQualifier(key.getAnnotationType(), getValueAttributeForNamed(key)));
|
||||
bean.addQualifier(new AutowireCandidateQualifier(Qualifier.class, getValueAttributeForNamed(key)));
|
||||
bean.addQualifier(
|
||||
new AutowireCandidateQualifier(key.getAnnotationType(), getValueAttributeForNamed(key)));
|
||||
}
|
||||
if (ifLazyInit) {
|
||||
bean.setLazyInit(true);
|
||||
@@ -199,7 +200,7 @@ class ModuleRegistryConfiguration implements BeanDefinitionRegistryPostProcessor
|
||||
else if (key.getAnnotation() instanceof javax.inject.Named) {
|
||||
return ((javax.inject.Named) key.getAnnotation()).value();
|
||||
}
|
||||
else if (key.getAnnotationType() != null){
|
||||
else if (key.getAnnotationType() != null) {
|
||||
return key.getAnnotationType().getName();
|
||||
}
|
||||
else {
|
||||
@@ -207,22 +208,22 @@ class ModuleRegistryConfiguration implements BeanDefinitionRegistryPostProcessor
|
||||
}
|
||||
}
|
||||
|
||||
private boolean elementFilter(String[] modulesToFilter, Element element){
|
||||
private boolean elementFilter(String[] modulesToFilter, Element element) {
|
||||
try {
|
||||
return Arrays.stream(modulesToFilter)
|
||||
.noneMatch(ex -> Optional.of(element).map(Element::getSource).map(Object::toString).orElse("").contains(ex));
|
||||
} catch (Exception e){
|
||||
logger.error(String.format("Unable fo filter element[%s] with filter [%s]", element, Arrays.toString(modulesToFilter)), e);
|
||||
return Arrays.stream(modulesToFilter).noneMatch(
|
||||
ex -> Optional.of(element).map(Element::getSource).map(Object::toString).orElse("").contains(ex));
|
||||
}
|
||||
catch (Exception e) {
|
||||
logger.error(String.format("Unable fo filter element[%s] with filter [%s]", element,
|
||||
Arrays.toString(modulesToFilter)), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void extractPrivateElements(Map<Key<?>, Binding<?>> bindings,
|
||||
PrivateElements privateElements) {
|
||||
private void extractPrivateElements(Map<Key<?>, Binding<?>> bindings, PrivateElements privateElements) {
|
||||
List<Element> elements = privateElements.getElements();
|
||||
for (Element e : elements) {
|
||||
if (e instanceof Binding && privateElements.getExposedKeys()
|
||||
.contains(((Binding<?>) e).getKey())) {
|
||||
if (e instanceof Binding && privateElements.getExposedKeys().contains(((Binding<?>) e).getKey())) {
|
||||
Binding<?> binding = (Binding<?>) e;
|
||||
bindings.put(binding.getKey(), binding);
|
||||
}
|
||||
@@ -237,22 +238,21 @@ class ModuleRegistryConfiguration implements BeanDefinitionRegistryPostProcessor
|
||||
* for a given binding key
|
||||
*/
|
||||
protected List<Element> removeDuplicates(List<Element> elements) {
|
||||
List<Element> duplicateElements = elements.stream()
|
||||
.filter(e -> e instanceof Binding).map(e -> (Binding<?>) e)
|
||||
List<Element> duplicateElements = elements.stream().filter(e -> e instanceof Binding).map(e -> (Binding<?>) e)
|
||||
.collect(Collectors.groupingBy(ModuleRegistryConfiguration::getLinkedKeyIfRequired)).entrySet().stream()
|
||||
.filter(e -> e.getValue().size() > 1 && e.getValue().stream().anyMatch(
|
||||
binding -> binding.getSource() != null && binding.getSource()
|
||||
.toString().contains(SpringModule.SPRING_GUICE_SOURCE))) // find duplicates
|
||||
.filter(e -> e.getValue().size() > 1 && e.getValue().stream()
|
||||
.anyMatch(binding -> binding.getSource() != null
|
||||
&& binding.getSource().toString().contains(SpringModule.SPRING_GUICE_SOURCE))) // find
|
||||
// duplicates
|
||||
.flatMap(e -> e.getValue().stream())
|
||||
.filter(e -> e.getSource() != null && !e.getSource().toString()
|
||||
.contains(SpringModule.SPRING_GUICE_SOURCE))
|
||||
.filter(e -> e.getSource() != null
|
||||
&& !e.getSource().toString().contains(SpringModule.SPRING_GUICE_SOURCE))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
@SuppressWarnings("unlikely-arg-type")
|
||||
List<Element> dedupedElements = elements.stream().filter(e -> {
|
||||
if (e instanceof Binding) {
|
||||
return !duplicateElements
|
||||
.contains(new SourceComparableBinding((Binding<?>) e));
|
||||
return !duplicateElements.contains(new SourceComparableBinding((Binding<?>) e));
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
@@ -275,6 +275,7 @@ class ModuleRegistryConfiguration implements BeanDefinitionRegistryPostProcessor
|
||||
}
|
||||
|
||||
private static class SourceComparableBinding {
|
||||
|
||||
private Binding<?> binding;
|
||||
|
||||
public SourceComparableBinding(Binding<?> binding) {
|
||||
@@ -286,8 +287,7 @@ class ModuleRegistryConfiguration implements BeanDefinitionRegistryPostProcessor
|
||||
if (obj instanceof Binding) {
|
||||
Binding<?> compareTo = (Binding<?>) obj;
|
||||
if (compareTo.getSource() != null && this.binding != null) {
|
||||
return binding.equals(compareTo)
|
||||
&& Objects.equals(binding.getSource(), compareTo.getSource());
|
||||
return binding.equals(compareTo) && Objects.equals(binding.getSource(), compareTo.getSource());
|
||||
}
|
||||
else {
|
||||
return Objects.equals(binding, compareTo);
|
||||
@@ -297,29 +297,37 @@ class ModuleRegistryConfiguration implements BeanDefinitionRegistryPostProcessor
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the Guice injector and registers it.
|
||||
*
|
||||
* The correct time to create the injector is after all Bean Post Processors were registered (after the
|
||||
* registerBeanPostProcessors() phase), but before other beans get resolved. To achieve this, we create the injector
|
||||
* when the first bean gets resolved - in its post-processing phase. However, this creates a possibility for a circular
|
||||
* initialization error (i.e. if the first bean is also being dependant on by a Guice provided binding). To resolve
|
||||
* this we publish an event that will be triggered in the registerListeners() phase, and create the injector then.
|
||||
* Combining both initialization mechanisms (post-processor and the event publishing) ensures the injector will be
|
||||
* created no later then the registerListeners() phase, but after the registerBeanPostProcessors() phase.
|
||||
* For application contexts that override onRefresh() and create beans then (i.e. WebServer based application contexts)
|
||||
* the post-processor initialization will kick-in and create the injector before.
|
||||
* The correct time to create the injector is after all Bean Post Processors were
|
||||
* registered (after the registerBeanPostProcessors() phase), but before other beans get
|
||||
* resolved. To achieve this, we create the injector when the first bean gets resolved -
|
||||
* in its post-processing phase. However, this creates a possibility for a circular
|
||||
* initialization error (i.e. if the first bean is also being dependant on by a Guice
|
||||
* provided binding). To resolve this we publish an event that will be triggered in the
|
||||
* registerListeners() phase, and create the injector then. Combining both initialization
|
||||
* mechanisms (post-processor and the event publishing) ensures the injector will be
|
||||
* created no later then the registerListeners() phase, but after the
|
||||
* registerBeanPostProcessors() phase. For application contexts that override onRefresh()
|
||||
* and create beans then (i.e. WebServer based application contexts) the post-processor
|
||||
* initialization will kick-in and create the injector before.
|
||||
*/
|
||||
class GuiceInjectorInitializer implements BeanPostProcessor, ApplicationListener<GuiceInjectorInitializer.CreateInjectorEvent> {
|
||||
class GuiceInjectorInitializer
|
||||
implements BeanPostProcessor, ApplicationListener<GuiceInjectorInitializer.CreateInjectorEvent> {
|
||||
|
||||
private final AtomicBoolean injectorCreated = new AtomicBoolean(false);
|
||||
|
||||
private final List<Module> modules;
|
||||
|
||||
private final ConfigurableApplicationContext applicationContext;
|
||||
|
||||
public GuiceInjectorInitializer(List<Module> modules,
|
||||
ConfigurableApplicationContext applicationContext) {
|
||||
public GuiceInjectorInitializer(List<Module> modules, ConfigurableApplicationContext applicationContext) {
|
||||
this.modules = modules;
|
||||
this.applicationContext = applicationContext;
|
||||
|
||||
@@ -346,8 +354,7 @@ class GuiceInjectorInitializer implements BeanPostProcessor, ApplicationListener
|
||||
try {
|
||||
Map<String, InjectorFactory> beansOfType = applicationContext.getBeansOfType(InjectorFactory.class);
|
||||
if (beansOfType.size() > 1) {
|
||||
throw new ApplicationContextException("Found multiple beans of type "
|
||||
+ InjectorFactory.class.getName()
|
||||
throw new ApplicationContextException("Found multiple beans of type " + InjectorFactory.class.getName()
|
||||
+ " Please ensure that only one InjectorFactory bean is defined. InjectorFactory beans found: "
|
||||
+ beansOfType.keySet());
|
||||
}
|
||||
@@ -367,12 +374,13 @@ class GuiceInjectorInitializer implements BeanPostProcessor, ApplicationListener
|
||||
}
|
||||
|
||||
static class CreateInjectorEvent extends ApplicationEvent {
|
||||
|
||||
private static final long serialVersionUID = -6546970378679850504L;
|
||||
|
||||
public CreateInjectorEvent() {
|
||||
super(serialVersionUID);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -37,16 +37,17 @@ import com.google.inject.name.Named;
|
||||
import com.google.inject.spi.TypeConverterBinding;
|
||||
|
||||
/**
|
||||
* An {@link Injector} that wraps an {@link ApplicationContext}, and can be used
|
||||
* to expose the Guice APIs over a Spring application. Does not use Guice at all
|
||||
* internally: just adapts the Spring API to the Guice one.
|
||||
*
|
||||
* An {@link Injector} that wraps an {@link ApplicationContext}, and can be used to expose
|
||||
* the Guice APIs over a Spring application. Does not use Guice at all internally: just
|
||||
* adapts the Spring API to the Guice one.
|
||||
*
|
||||
* @author Dave Syer
|
||||
*
|
||||
*/
|
||||
public class SpringInjector implements Injector {
|
||||
|
||||
private Injector injector;
|
||||
|
||||
private DefaultListableBeanFactory beanFactory;
|
||||
|
||||
public SpringInjector(ApplicationContext context) {
|
||||
@@ -134,8 +135,9 @@ public class SpringInjector implements Injector {
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public T get() {
|
||||
if(key.getAnnotation() != null) {
|
||||
return (T) BeanFactoryAnnotationUtils.qualifiedBeanOfType(SpringInjector.this.beanFactory, type, name);
|
||||
if (key.getAnnotation() != null) {
|
||||
return (T) BeanFactoryAnnotationUtils.qualifiedBeanOfType(SpringInjector.this.beanFactory, type,
|
||||
name);
|
||||
}
|
||||
return SpringInjector.this.beanFactory.getBean(cls);
|
||||
}
|
||||
@@ -146,7 +148,8 @@ public class SpringInjector implements Injector {
|
||||
final Annotation annotation = key.getAnnotation();
|
||||
if (annotation instanceof Named) {
|
||||
return ((Named) annotation).value();
|
||||
} else if (annotation instanceof javax.inject.Named) {
|
||||
}
|
||||
else if (annotation instanceof javax.inject.Named) {
|
||||
return ((javax.inject.Named) annotation).value();
|
||||
}
|
||||
return key.getTypeLiteral().getRawType().getSimpleName();
|
||||
|
||||
@@ -50,21 +50,22 @@ import org.springframework.core.OrderComparator;
|
||||
* register an {@link ApplicationContextInitializer} that sets a shutdown hook, so that
|
||||
* the context is closed automatically when the JVM ends.
|
||||
* </p>
|
||||
*
|
||||
*
|
||||
* @author Dave Syer
|
||||
*
|
||||
*/
|
||||
public class BeanFactoryProvider
|
||||
implements Provider<ConfigurableListableBeanFactory>, Closeable {
|
||||
public class BeanFactoryProvider implements Provider<ConfigurableListableBeanFactory>, Closeable {
|
||||
|
||||
private Class<?>[] config;
|
||||
|
||||
private String[] basePackages;
|
||||
|
||||
private List<ApplicationContextInitializer<ConfigurableApplicationContext>> initializers = new ArrayList<ApplicationContextInitializer<ConfigurableApplicationContext>>();
|
||||
|
||||
private PartiallyRefreshableApplicationContext context;
|
||||
|
||||
/**
|
||||
* Create an application context by scanning these base packages.
|
||||
*
|
||||
* @param basePackages base packages to scan
|
||||
* @return a provider
|
||||
*/
|
||||
@@ -74,7 +75,6 @@ public class BeanFactoryProvider
|
||||
|
||||
/**
|
||||
* Create an application context using these configuration classes.
|
||||
*
|
||||
* @param config classes to build an application
|
||||
* @return a provider
|
||||
*/
|
||||
@@ -132,8 +132,7 @@ public class BeanFactoryProvider
|
||||
return context.getBeanFactory();
|
||||
}
|
||||
|
||||
private static final class PartiallyRefreshableApplicationContext
|
||||
extends AnnotationConfigApplicationContext {
|
||||
private static final class PartiallyRefreshableApplicationContext extends AnnotationConfigApplicationContext {
|
||||
|
||||
private final AtomicBoolean partiallyRefreshed = new AtomicBoolean(false);
|
||||
|
||||
@@ -143,8 +142,7 @@ public class BeanFactoryProvider
|
||||
*/
|
||||
private void partialRefresh() {
|
||||
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
|
||||
beanFactory.registerSingleton("refreshListener",
|
||||
new ContextRefreshingProvisionListener(this));
|
||||
beanFactory.registerSingleton("refreshListener", new ContextRefreshingProvisionListener(this));
|
||||
prepareBeanFactory(beanFactory);
|
||||
invokeBeanFactoryPostProcessors(beanFactory);
|
||||
}
|
||||
@@ -158,21 +156,21 @@ public class BeanFactoryProvider
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void invokeBeanFactoryPostProcessors(
|
||||
ConfigurableListableBeanFactory beanFactory) {
|
||||
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
|
||||
if (partiallyRefreshed.compareAndSet(false, true)) {
|
||||
super.invokeBeanFactoryPostProcessors(beanFactory);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static final class ContextRefreshingProvisionListener
|
||||
implements ProvisionListener {
|
||||
private static final class ContextRefreshingProvisionListener implements ProvisionListener {
|
||||
|
||||
private final PartiallyRefreshableApplicationContext context;
|
||||
|
||||
private final AtomicBoolean initialized = new AtomicBoolean(false);
|
||||
|
||||
private ContextRefreshingProvisionListener(
|
||||
PartiallyRefreshableApplicationContext context) {
|
||||
private ContextRefreshingProvisionListener(PartiallyRefreshableApplicationContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
@@ -183,6 +181,7 @@ public class BeanFactoryProvider
|
||||
}
|
||||
provision.provision();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -35,7 +35,6 @@ import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
* @author Taylor Wicksell
|
||||
@@ -44,101 +43,107 @@ import java.util.concurrent.atomic.AtomicReference;
|
||||
*/
|
||||
class GuiceAutowireCandidateResolver extends ContextAnnotationAutowireCandidateResolver {
|
||||
|
||||
private Provider<Injector> injectorProvider;
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
private Provider<Injector> injectorProvider;
|
||||
|
||||
public GuiceAutowireCandidateResolver(Provider<Injector> injectorProvider) {
|
||||
this.injectorProvider = injectorProvider;
|
||||
addQualifierType(BindingAnnotation.class);
|
||||
}
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
@Override
|
||||
public Object getLazyResolutionProxyIfNecessary(DependencyDescriptor descriptor, String beanName) {
|
||||
return (isLazy(descriptor, beanName) ? buildLazyResolutionProxy(descriptor, beanName) : null);
|
||||
}
|
||||
public GuiceAutowireCandidateResolver(Provider<Injector> injectorProvider) {
|
||||
this.injectorProvider = injectorProvider;
|
||||
addQualifierType(BindingAnnotation.class);
|
||||
}
|
||||
|
||||
protected boolean isLazy(DependencyDescriptor descriptor, String beanName) {
|
||||
Assert.state(getBeanFactory() instanceof DefaultListableBeanFactory,
|
||||
"BeanFactory needs to be a DefaultListableBeanFactory");
|
||||
final DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) getBeanFactory();
|
||||
@Override
|
||||
public Object getLazyResolutionProxyIfNecessary(DependencyDescriptor descriptor, String beanName) {
|
||||
return (isLazy(descriptor, beanName) ? buildLazyResolutionProxy(descriptor, beanName) : null);
|
||||
}
|
||||
|
||||
if (isCollectionType(descriptor.getDependencyType())) {
|
||||
return false;
|
||||
}
|
||||
protected boolean isLazy(DependencyDescriptor descriptor, String beanName) {
|
||||
Assert.state(getBeanFactory() instanceof DefaultListableBeanFactory,
|
||||
"BeanFactory needs to be a DefaultListableBeanFactory");
|
||||
final DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) getBeanFactory();
|
||||
|
||||
if (super.isLazy(descriptor)) {
|
||||
return true;
|
||||
}
|
||||
if (isCollectionType(descriptor.getDependencyType())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
beanFactory.doResolveDependency(descriptor, beanName, null, null);
|
||||
} catch (NoSuchBeanDefinitionException e) {
|
||||
if (e.getResolvableType() != null) {
|
||||
logger.info(String.format("Use just in time binding for %s in bean: %s",
|
||||
e.getResolvableType().getType().getTypeName(), beanName));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (super.isLazy(descriptor)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
beanFactory.doResolveDependency(descriptor, beanName, null, null);
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException e) {
|
||||
if (e.getResolvableType() != null) {
|
||||
logger.info(String.format("Use just in time binding for %s in bean: %s",
|
||||
e.getResolvableType().getType().getTypeName(), beanName));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
protected Object buildLazyResolutionProxy(final DependencyDescriptor descriptor, final String beanName) {
|
||||
Assert.state(getBeanFactory() instanceof DefaultListableBeanFactory,
|
||||
"BeanFactory needs to be a DefaultListableBeanFactory");
|
||||
final DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) getBeanFactory();
|
||||
TargetSource ts = new TargetSource() {
|
||||
private Optional<Boolean> isGuiceResolvable = Optional.empty();
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<?> getTargetClass() {
|
||||
return descriptor.getDependencyType();
|
||||
}
|
||||
protected Object buildLazyResolutionProxy(final DependencyDescriptor descriptor, final String beanName) {
|
||||
Assert.state(getBeanFactory() instanceof DefaultListableBeanFactory,
|
||||
"BeanFactory needs to be a DefaultListableBeanFactory");
|
||||
final DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) getBeanFactory();
|
||||
TargetSource ts = new TargetSource() {
|
||||
private Optional<Boolean> isGuiceResolvable = Optional.empty();
|
||||
|
||||
@Override
|
||||
public boolean isStatic() {
|
||||
return false;
|
||||
}
|
||||
@Override
|
||||
public Class<?> getTargetClass() {
|
||||
return descriptor.getDependencyType();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getTarget() {
|
||||
Object target = null;
|
||||
if (isGuiceResolvable.isPresent() && isGuiceResolvable.get()) {
|
||||
target = injectorProvider.get().getInstance(Key.get(descriptor.getResolvableType().getType()));
|
||||
} else {
|
||||
try {
|
||||
target = beanFactory.doResolveDependency(descriptor, beanName, null, null);
|
||||
} catch (NoSuchBeanDefinitionException e) {
|
||||
target = injectorProvider.get().getInstance(Key.get(descriptor.getResolvableType().getType()));
|
||||
isGuiceResolvable = Optional.of(true);
|
||||
}
|
||||
}
|
||||
if (target == null) {
|
||||
throw new NoSuchBeanDefinitionException(descriptor.getDependencyType(),
|
||||
"Optional dependency not present for lazy injection point");
|
||||
}
|
||||
return target;
|
||||
}
|
||||
@Override
|
||||
public boolean isStatic() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void releaseTarget(Object target) {
|
||||
}
|
||||
};
|
||||
try {
|
||||
ProxyFactory pf = new ProxyFactory();
|
||||
pf.setTargetSource(ts);
|
||||
Class<?> dependencyType = descriptor.getDependencyType();
|
||||
if (dependencyType.isInterface()) {
|
||||
pf.addInterface(dependencyType);
|
||||
}
|
||||
return pf.getProxy(beanFactory.getBeanClassLoader());
|
||||
} catch(Exception e) {
|
||||
logger.debug("Failed to build lazy resolution proxy to Guice", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public Object getTarget() {
|
||||
Object target = null;
|
||||
if (isGuiceResolvable.isPresent() && isGuiceResolvable.get()) {
|
||||
target = injectorProvider.get().getInstance(Key.get(descriptor.getResolvableType().getType()));
|
||||
}
|
||||
else {
|
||||
try {
|
||||
target = beanFactory.doResolveDependency(descriptor, beanName, null, null);
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException e) {
|
||||
target = injectorProvider.get().getInstance(Key.get(descriptor.getResolvableType().getType()));
|
||||
isGuiceResolvable = Optional.of(true);
|
||||
}
|
||||
}
|
||||
if (target == null) {
|
||||
throw new NoSuchBeanDefinitionException(descriptor.getDependencyType(),
|
||||
"Optional dependency not present for lazy injection point");
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void releaseTarget(Object target) {
|
||||
}
|
||||
};
|
||||
try {
|
||||
ProxyFactory pf = new ProxyFactory();
|
||||
pf.setTargetSource(ts);
|
||||
Class<?> dependencyType = descriptor.getDependencyType();
|
||||
if (dependencyType.isInterface()) {
|
||||
pf.addInterface(dependencyType);
|
||||
}
|
||||
return pf.getProxy(beanFactory.getBeanClassLoader());
|
||||
}
|
||||
catch (Exception e) {
|
||||
logger.debug("Failed to build lazy resolution proxy to Guice", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean isCollectionType(Class<?> type) {
|
||||
return Collection.class.isAssignableFrom(type) || Map.class == type;
|
||||
}
|
||||
|
||||
private boolean isCollectionType(Class<?> type) {
|
||||
return Collection.class.isAssignableFrom(type) || Map.class == type;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ import org.springframework.util.PatternMatchUtils;
|
||||
* Encapsulates some metadata about a Guice module that is to be created from a Spring
|
||||
* application context. Can be used directly as a <code>@Bean</code>, but it is easier to
|
||||
* just add <code>@</code> {@link GuiceModule} to your <code>@Configuration</code>.
|
||||
*
|
||||
*
|
||||
* @author Dave Syer
|
||||
*
|
||||
*/
|
||||
@@ -97,7 +97,7 @@ public class GuiceModuleMetadata implements BindingTypeMatcher {
|
||||
|
||||
@Override
|
||||
public boolean matches(String name, Type type) {
|
||||
Type rawType = type instanceof ParameterizedType ? ((ParameterizedType)type).getRawType() : type;
|
||||
Type rawType = type instanceof ParameterizedType ? ((ParameterizedType) type).getRawType() : type;
|
||||
if (!matches(name) || !matches(rawType)) {
|
||||
return false;
|
||||
}
|
||||
@@ -143,30 +143,28 @@ public class GuiceModuleMetadata implements BindingTypeMatcher {
|
||||
|
||||
if (includeFilters != null) {
|
||||
try {
|
||||
MetadataReader reader = metadataReaderFactory.getMetadataReader(type
|
||||
.getTypeName());
|
||||
MetadataReader reader = metadataReaderFactory.getMetadataReader(type.getTypeName());
|
||||
for (TypeFilter filter : includeFilters) {
|
||||
if (!filter.match(reader, metadataReaderFactory)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Cannot read metadata for class " + type,
|
||||
e);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new IllegalStateException("Cannot read metadata for class " + type, e);
|
||||
}
|
||||
}
|
||||
if (excludeFilters != null) {
|
||||
try {
|
||||
MetadataReader reader = metadataReaderFactory.getMetadataReader(type
|
||||
.getTypeName());
|
||||
MetadataReader reader = metadataReaderFactory.getMetadataReader(type.getTypeName());
|
||||
for (TypeFilter filter : excludeFilters) {
|
||||
if (filter.match(reader, metadataReaderFactory)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Cannot read metadata for class " + type,
|
||||
e);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new IllegalStateException("Cannot read metadata for class " + type, e);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
@@ -175,8 +173,7 @@ public class GuiceModuleMetadata implements BindingTypeMatcher {
|
||||
private boolean visible(Type type) {
|
||||
Class<?> cls = ResolvableType.forType(type).resolve();
|
||||
while (cls != null && cls != Object.class) {
|
||||
if (!Modifier.isInterface(cls.getModifiers())
|
||||
&& !Modifier.isPublic(cls.getModifiers())
|
||||
if (!Modifier.isInterface(cls.getModifiers()) && !Modifier.isPublic(cls.getModifiers())
|
||||
&& !Modifier.isProtected(cls.getModifiers())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -84,16 +84,14 @@ public class SpringModule extends AbstractModule {
|
||||
}
|
||||
|
||||
public SpringModule(ApplicationContext context, boolean enableJustInTimeBinding) {
|
||||
this((ConfigurableListableBeanFactory) context.getAutowireCapableBeanFactory(),
|
||||
enableJustInTimeBinding);
|
||||
this((ConfigurableListableBeanFactory) context.getAutowireCapableBeanFactory(), enableJustInTimeBinding);
|
||||
}
|
||||
|
||||
public SpringModule(ConfigurableListableBeanFactory beanFactory) {
|
||||
this(beanFactory, true);
|
||||
}
|
||||
|
||||
public SpringModule(ConfigurableListableBeanFactory beanFactory,
|
||||
boolean enableJustInTimeBinding) {
|
||||
public SpringModule(ConfigurableListableBeanFactory beanFactory, boolean enableJustInTimeBinding) {
|
||||
this.beanFactory = beanFactory;
|
||||
this.enableJustInTimeBinding = enableJustInTimeBinding;
|
||||
}
|
||||
@@ -109,19 +107,16 @@ public class SpringModule extends AbstractModule {
|
||||
}
|
||||
if (beanFactory.getBeanNamesForType(ProvisionListener.class).length > 0) {
|
||||
binder().bindListener(Matchers.any(),
|
||||
beanFactory.getBeansOfType(ProvisionListener.class).values()
|
||||
.toArray(new ProvisionListener[0]));
|
||||
beanFactory.getBeansOfType(ProvisionListener.class).values().toArray(new ProvisionListener[0]));
|
||||
}
|
||||
if (enableJustInTimeBinding) {
|
||||
if (beanFactory instanceof DefaultListableBeanFactory) {
|
||||
((DefaultListableBeanFactory) beanFactory)
|
||||
.setAutowireCandidateResolver(new GuiceAutowireCandidateResolver(
|
||||
binder().getProvider(Injector.class)));
|
||||
((DefaultListableBeanFactory) beanFactory).setAutowireCandidateResolver(
|
||||
new GuiceAutowireCandidateResolver(binder().getProvider(Injector.class)));
|
||||
}
|
||||
}
|
||||
if (beanFactory.getBeanNamesForType(GuiceModuleMetadata.class).length > 0) {
|
||||
this.matcher = new CompositeTypeMatcher(
|
||||
beanFactory.getBeansOfType(GuiceModuleMetadata.class).values());
|
||||
this.matcher = new CompositeTypeMatcher(beanFactory.getBeansOfType(GuiceModuleMetadata.class).values());
|
||||
}
|
||||
bind(beanFactory);
|
||||
}
|
||||
@@ -133,10 +128,8 @@ public class SpringModule extends AbstractModule {
|
||||
if (definition.hasAttribute(SPRING_GUICE_SOURCE)) {
|
||||
continue;
|
||||
}
|
||||
Optional<Annotation> bindingAnnotation = getAnnotationForBeanDefinition(
|
||||
definition, beanFactory);
|
||||
if (definition.isAutowireCandidate()
|
||||
&& definition.getRole() == AbstractBeanDefinition.ROLE_APPLICATION) {
|
||||
Optional<Annotation> bindingAnnotation = getAnnotationForBeanDefinition(definition, beanFactory);
|
||||
if (definition.isAutowireCandidate() && definition.getRole() == AbstractBeanDefinition.ROLE_APPLICATION) {
|
||||
Type type;
|
||||
Class<?> clazz = beanFactory.getType(name);
|
||||
if (clazz == null) {
|
||||
@@ -147,53 +140,47 @@ public class SpringModule extends AbstractModule {
|
||||
.getMergedBeanDefinition(name);
|
||||
if (rootBeanDefinition.getFactoryBeanName() != null
|
||||
&& rootBeanDefinition.getResolvedFactoryMethod() != null) {
|
||||
type = rootBeanDefinition.getResolvedFactoryMethod()
|
||||
.getGenericReturnType();
|
||||
type = rootBeanDefinition.getResolvedFactoryMethod().getGenericReturnType();
|
||||
}
|
||||
else {
|
||||
type = rootBeanDefinition.getResolvableType().getType();
|
||||
}
|
||||
if (type instanceof ParameterizedType) {
|
||||
ParameterizedType parameterizedType = (ParameterizedType) type;
|
||||
if (parameterizedType.getRawType() instanceof Class &&
|
||||
FactoryBean.class.isAssignableFrom((Class<?>) parameterizedType.getRawType())) {
|
||||
type = Types.newParameterizedTypeWithOwner(parameterizedType.getOwnerType(),
|
||||
clazz, parameterizedType.getActualTypeArguments());
|
||||
if (parameterizedType.getRawType() instanceof Class
|
||||
&& FactoryBean.class.isAssignableFrom((Class<?>) parameterizedType.getRawType())) {
|
||||
type = Types.newParameterizedTypeWithOwner(parameterizedType.getOwnerType(), clazz,
|
||||
parameterizedType.getActualTypeArguments());
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
type = clazz;
|
||||
}
|
||||
|
||||
if (type == null) {
|
||||
continue;
|
||||
}
|
||||
Provider<?> typeProvider = BeanFactoryProvider.typed(beanFactory, type,
|
||||
bindingAnnotation);
|
||||
Provider<?> namedProvider = BeanFactoryProvider.named(beanFactory,
|
||||
name, type, bindingAnnotation);
|
||||
Provider<?> typeProvider = BeanFactoryProvider.typed(beanFactory, type, bindingAnnotation);
|
||||
Provider<?> namedProvider = BeanFactoryProvider.named(beanFactory, name, type, bindingAnnotation);
|
||||
|
||||
if (!clazz.isInterface() && !ClassUtils.isCglibProxyClass(clazz)) {
|
||||
bindConditionally(binder(), name, clazz, typeProvider, namedProvider,
|
||||
bindingAnnotation);
|
||||
bindConditionally(binder(), name, clazz, typeProvider, namedProvider, bindingAnnotation);
|
||||
}
|
||||
for (Type superType : getAllSuperTypes(type, clazz)) {
|
||||
if (!ClassUtils.isCglibProxyClassName(superType.getTypeName())) {
|
||||
bindConditionally(binder(), name, superType, typeProvider,
|
||||
namedProvider, bindingAnnotation);
|
||||
bindConditionally(binder(), name, superType, typeProvider, namedProvider, bindingAnnotation);
|
||||
}
|
||||
}
|
||||
for (Type iface : clazz.getGenericInterfaces()) {
|
||||
bindConditionally(binder(), name, iface, typeProvider, namedProvider,
|
||||
bindingAnnotation);
|
||||
bindConditionally(binder(), name, iface, typeProvider, namedProvider, bindingAnnotation);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String getNameFromBindingAnnotation(
|
||||
Optional<Annotation> bindingAnnotation) {
|
||||
private static String getNameFromBindingAnnotation(Optional<Annotation> bindingAnnotation) {
|
||||
if (bindingAnnotation.isPresent()) {
|
||||
Annotation annotation = bindingAnnotation.get();
|
||||
if (annotation instanceof Named) {
|
||||
@@ -211,16 +198,14 @@ public class SpringModule extends AbstractModule {
|
||||
}
|
||||
}
|
||||
|
||||
private static Optional<Annotation> getAnnotationForBeanDefinition(
|
||||
BeanDefinition definition, ConfigurableListableBeanFactory beanFactory) {
|
||||
private static Optional<Annotation> getAnnotationForBeanDefinition(BeanDefinition definition,
|
||||
ConfigurableListableBeanFactory beanFactory) {
|
||||
if (definition instanceof AnnotatedBeanDefinition
|
||||
&& ((AnnotatedBeanDefinition) definition)
|
||||
.getFactoryMethodMetadata() != null) {
|
||||
&& ((AnnotatedBeanDefinition) definition).getFactoryMethodMetadata() != null) {
|
||||
try {
|
||||
Method factoryMethod = getFactoryMethod(beanFactory, definition);
|
||||
return Arrays.stream(AnnotationUtils.getAnnotations(factoryMethod))
|
||||
.filter(a -> Annotations.isBindingAnnotation(a.annotationType()))
|
||||
.findFirst();
|
||||
.filter(a -> Annotations.isBindingAnnotation(a.annotationType())).findFirst();
|
||||
}
|
||||
catch (Exception e) {
|
||||
return Optional.empty();
|
||||
@@ -231,25 +216,21 @@ public class SpringModule extends AbstractModule {
|
||||
}
|
||||
}
|
||||
|
||||
private static Method getFactoryMethod(ConfigurableListableBeanFactory beanFactory,
|
||||
BeanDefinition definition) throws Exception {
|
||||
private static Method getFactoryMethod(ConfigurableListableBeanFactory beanFactory, BeanDefinition definition)
|
||||
throws Exception {
|
||||
if (definition instanceof AnnotatedBeanDefinition) {
|
||||
MethodMetadata factoryMethodMetadata = ((AnnotatedBeanDefinition) definition)
|
||||
.getFactoryMethodMetadata();
|
||||
MethodMetadata factoryMethodMetadata = ((AnnotatedBeanDefinition) definition).getFactoryMethodMetadata();
|
||||
if (factoryMethodMetadata instanceof StandardMethodMetadata) {
|
||||
return ((StandardMethodMetadata) factoryMethodMetadata)
|
||||
.getIntrospectedMethod();
|
||||
return ((StandardMethodMetadata) factoryMethodMetadata).getIntrospectedMethod();
|
||||
}
|
||||
}
|
||||
BeanDefinition factoryDefinition = beanFactory
|
||||
.getBeanDefinition(definition.getFactoryBeanName());
|
||||
BeanDefinition factoryDefinition = beanFactory.getBeanDefinition(definition.getFactoryBeanName());
|
||||
Class<?> factoryClass = ClassUtils.forName(factoryDefinition.getBeanClassName(),
|
||||
beanFactory.getBeanClassLoader());
|
||||
return getFactoryMethod(definition, factoryClass);
|
||||
}
|
||||
|
||||
private static Method getFactoryMethod(BeanDefinition definition,
|
||||
Class<?> factoryClass) {
|
||||
private static Method getFactoryMethod(BeanDefinition definition, Class<?> factoryClass) {
|
||||
Method uniqueMethod = null;
|
||||
for (Method candidate : getCandidateFactoryMethods(definition, factoryClass)) {
|
||||
if (candidate.getName().equals(definition.getFactoryMethodName())) {
|
||||
@@ -264,10 +245,8 @@ public class SpringModule extends AbstractModule {
|
||||
return uniqueMethod;
|
||||
}
|
||||
|
||||
private static Method[] getCandidateFactoryMethods(BeanDefinition definition,
|
||||
Class<?> factoryClass) {
|
||||
return shouldConsiderNonPublicMethods(definition)
|
||||
? ReflectionUtils.getAllDeclaredMethods(factoryClass)
|
||||
private static Method[] getCandidateFactoryMethods(BeanDefinition definition, Class<?> factoryClass) {
|
||||
return shouldConsiderNonPublicMethods(definition) ? ReflectionUtils.getAllDeclaredMethods(factoryClass)
|
||||
: factoryClass.getMethods();
|
||||
}
|
||||
|
||||
@@ -293,10 +272,8 @@ public class SpringModule extends AbstractModule {
|
||||
allInterfaces.add(type);
|
||||
if (type instanceof Class) {
|
||||
for (Type i : ((Class<?>) type).getInterfaces()) {
|
||||
if (i instanceof Class
|
||||
&& ((Class<?>) i).isAssignableFrom(typeToken.getRawType())) {
|
||||
Type superInterface = typeToken.getSupertype((Class<?>) i)
|
||||
.getType();
|
||||
if (i instanceof Class && ((Class<?>) i).isAssignableFrom(typeToken.getRawType())) {
|
||||
Type superInterface = typeToken.getSupertype((Class<?>) i).getType();
|
||||
queue.add(superInterface);
|
||||
if (!(superInterface instanceof Class)) {
|
||||
queue.add(i);
|
||||
@@ -305,8 +282,7 @@ public class SpringModule extends AbstractModule {
|
||||
}
|
||||
if (((Class<?>) type).getSuperclass() != null
|
||||
&& ((Class<?>) type).isAssignableFrom(typeToken.getRawType())) {
|
||||
Type superClass = typeToken
|
||||
.getSupertype(((Class<?>) type).getSuperclass()).getType();
|
||||
Type superClass = typeToken.getSupertype(((Class<?>) type).getSuperclass()).getType();
|
||||
queue.add(superClass);
|
||||
}
|
||||
}
|
||||
@@ -315,8 +291,7 @@ public class SpringModule extends AbstractModule {
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
private void bindConditionally(Binder binder, String name, Type type,
|
||||
Provider typeProvider, Provider namedProvider,
|
||||
private void bindConditionally(Binder binder, String name, Type type, Provider typeProvider, Provider namedProvider,
|
||||
Optional<Annotation> bindingAnnotation) {
|
||||
if (!this.matcher.matches(name, type)) {
|
||||
return;
|
||||
@@ -332,8 +307,7 @@ public class SpringModule extends AbstractModule {
|
||||
}
|
||||
}
|
||||
}
|
||||
Key<?> key = bindingAnnotation.map(a -> (Key<Object>) Key.get(type, a))
|
||||
.orElse((Key<Object>) Key.get(type));
|
||||
Key<?> key = bindingAnnotation.map(a -> (Key<Object>) Key.get(type, a)).orElse((Key<Object>) Key.get(type));
|
||||
StageTypeKey stageTypeKey = new StageTypeKey(binder.currentStage(), key);
|
||||
if (this.bound.get(stageTypeKey) == null) {
|
||||
// Only bind one provider for each type
|
||||
@@ -343,14 +317,15 @@ public class SpringModule extends AbstractModule {
|
||||
}
|
||||
// But allow binding to named beans if not already bound
|
||||
if (!name.equals(getNameFromBindingAnnotation(bindingAnnotation))) {
|
||||
binder.withSource(SPRING_GUICE_SOURCE).bind(TypeLiteral.get(type))
|
||||
.annotatedWith(Names.named(name)).toProvider(namedProvider);
|
||||
binder.withSource(SPRING_GUICE_SOURCE).bind(TypeLiteral.get(type)).annotatedWith(Names.named(name))
|
||||
.toProvider(namedProvider);
|
||||
}
|
||||
}
|
||||
|
||||
private static class StageTypeKey {
|
||||
|
||||
private final Stage stage;
|
||||
|
||||
private Key<?> key;
|
||||
|
||||
public StageTypeKey(Stage stage, Key<?> key) {
|
||||
@@ -387,6 +362,7 @@ public class SpringModule extends AbstractModule {
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class BeanFactoryProvider implements Provider<Object> {
|
||||
@@ -401,21 +377,21 @@ public class SpringModule extends AbstractModule {
|
||||
|
||||
private Optional<Annotation> bindingAnnotation;
|
||||
|
||||
private BeanFactoryProvider(ConfigurableListableBeanFactory beanFactory,
|
||||
String name, Type type, Optional<Annotation> bindingAnnotation) {
|
||||
private BeanFactoryProvider(ConfigurableListableBeanFactory beanFactory, String name, Type type,
|
||||
Optional<Annotation> bindingAnnotation) {
|
||||
this.beanFactory = beanFactory;
|
||||
this.name = name;
|
||||
this.bindingAnnotation = bindingAnnotation;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public static Provider<?> named(ConfigurableListableBeanFactory beanFactory,
|
||||
String name, Type type, Optional<Annotation> bindingAnnotation) {
|
||||
public static Provider<?> named(ConfigurableListableBeanFactory beanFactory, String name, Type type,
|
||||
Optional<Annotation> bindingAnnotation) {
|
||||
return new BeanFactoryProvider(beanFactory, name, type, bindingAnnotation);
|
||||
}
|
||||
|
||||
public static Provider<?> typed(ConfigurableListableBeanFactory beanFactory,
|
||||
Type type, Optional<Annotation> bindingAnnotation) {
|
||||
public static Provider<?> typed(ConfigurableListableBeanFactory beanFactory, Type type,
|
||||
Optional<Annotation> bindingAnnotation) {
|
||||
return new BeanFactoryProvider(beanFactory, null, type, bindingAnnotation);
|
||||
}
|
||||
|
||||
@@ -423,8 +399,8 @@ public class SpringModule extends AbstractModule {
|
||||
public Object get() {
|
||||
if (this.resultProvider == null) {
|
||||
|
||||
String[] named = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
|
||||
this.beanFactory, ResolvableType.forType(type));
|
||||
String[] named = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory,
|
||||
ResolvableType.forType(type));
|
||||
List<String> names = new ArrayList<String>(named.length);
|
||||
if (named.length == 1) {
|
||||
names.add(named[0]);
|
||||
@@ -433,17 +409,11 @@ public class SpringModule extends AbstractModule {
|
||||
for (String name : named) {
|
||||
if (bindingAnnotation.isPresent()) {
|
||||
if (bindingAnnotation.get() instanceof Named
|
||||
|| bindingAnnotation
|
||||
.get() instanceof javax.inject.Named) {
|
||||
Optional<Annotation> annotation = SpringModule
|
||||
.getAnnotationForBeanDefinition(
|
||||
beanFactory.getMergedBeanDefinition(name),
|
||||
beanFactory);
|
||||
String boundName = getNameFromBindingAnnotation(
|
||||
bindingAnnotation);
|
||||
if (annotation.isPresent()
|
||||
&& bindingAnnotation.get()
|
||||
.equals(annotation.get())
|
||||
|| bindingAnnotation.get() instanceof javax.inject.Named) {
|
||||
Optional<Annotation> annotation = SpringModule.getAnnotationForBeanDefinition(
|
||||
beanFactory.getMergedBeanDefinition(name), beanFactory);
|
||||
String boundName = getNameFromBindingAnnotation(bindingAnnotation);
|
||||
if (annotation.isPresent() && bindingAnnotation.get().equals(annotation.get())
|
||||
|| name.equals(boundName)) {
|
||||
names.add(name);
|
||||
}
|
||||
@@ -464,16 +434,17 @@ public class SpringModule extends AbstractModule {
|
||||
}
|
||||
}
|
||||
if (this.resultProvider == null) {
|
||||
throw new ProvisionException(
|
||||
"No primary bean definition for type: " + this.type);
|
||||
throw new ProvisionException("No primary bean definition for type: " + this.type);
|
||||
}
|
||||
}
|
||||
}
|
||||
return this.resultProvider.get();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class CompositeTypeMatcher implements BindingTypeMatcher {
|
||||
|
||||
private Collection<? extends BindingTypeMatcher> matchers;
|
||||
|
||||
public CompositeTypeMatcher(Collection<? extends BindingTypeMatcher> matchers) {
|
||||
@@ -489,5 +460,7 @@ public class SpringModule extends AbstractModule {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -75,17 +75,20 @@ public abstract class AbstractCompleteWiringTests {
|
||||
public void getNamedInjectedInstance() {
|
||||
assertNotNull(this.injector.getInstance(Thing.class).thang);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void getParameterizedType() {
|
||||
Parameterized<String> instance = this.injector.getInstance(Key.get(new TypeLiteral<Parameterized<String>>() {}));
|
||||
assertNotNull(instance);
|
||||
Parameterized<String> instance = this.injector.getInstance(Key.get(new TypeLiteral<Parameterized<String>>() {
|
||||
}));
|
||||
assertNotNull(instance);
|
||||
}
|
||||
|
||||
public interface Service {
|
||||
|
||||
}
|
||||
|
||||
public static class MyService implements Service {
|
||||
|
||||
}
|
||||
|
||||
public static class Foo {
|
||||
@@ -127,8 +130,11 @@ public abstract class AbstractCompleteWiringTests {
|
||||
}
|
||||
|
||||
public static class Thang {
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static interface Parameterized<T> {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -32,7 +32,8 @@ public class BeanPostProcessorTests {
|
||||
*/
|
||||
@Test
|
||||
public void testBeanPostProcessorsApplied() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanPostProcessorTestConfig.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
BeanPostProcessorTestConfig.class);
|
||||
PostProcessedBean postProcessedBean = context.getBean(PostProcessedBean.class);
|
||||
assertTrue(postProcessedBean.postProcessed);
|
||||
GuiceBeanThatWantsPostProcessedBean guiceBean1 = context.getBean(GuiceBeanThatWantsPostProcessedBean.class);
|
||||
@@ -41,41 +42,53 @@ public class BeanPostProcessorTests {
|
||||
assertTrue(guiceBean2.springBean.ppb.postProcessed);
|
||||
context.close();
|
||||
}
|
||||
|
||||
|
||||
public static class PostProcessedBean {
|
||||
|
||||
Boolean postProcessed = false;
|
||||
|
||||
}
|
||||
|
||||
public static class SpringBeanThatWantsPostProcessedBean {
|
||||
|
||||
PostProcessedBean ppb;
|
||||
|
||||
public SpringBeanThatWantsPostProcessedBean(PostProcessedBean ppb) {
|
||||
this.ppb = ppb;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class GuiceBeanThatWantsPostProcessedBean {
|
||||
|
||||
PostProcessedBean ppb;
|
||||
|
||||
@Inject
|
||||
public GuiceBeanThatWantsPostProcessedBean(PostProcessedBean ppb) {
|
||||
this.ppb = ppb;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class GuiceBeanThatWantsSpringBean {
|
||||
|
||||
SpringBeanThatWantsPostProcessedBean springBean;
|
||||
|
||||
@Inject
|
||||
public GuiceBeanThatWantsSpringBean(SpringBeanThatWantsPostProcessedBean springBean) {
|
||||
this.springBean = springBean;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@EnableGuiceModules
|
||||
@Configuration
|
||||
class BeanPostProcessorTestConfig {
|
||||
|
||||
|
||||
public static class PostProcessorRegistrar implements BeanDefinitionRegistryPostProcessor {
|
||||
|
||||
@Override
|
||||
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
|
||||
BeanDefinitionBuilder bean = BeanDefinitionBuilder.genericBeanDefinition(TestBeanPostProcessor.class);
|
||||
@@ -83,15 +96,17 @@ class BeanPostProcessorTestConfig {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {}
|
||||
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static class TestBeanPostProcessor implements BeanPostProcessor {
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
|
||||
if(bean instanceof PostProcessedBean) {
|
||||
((PostProcessedBean)bean).postProcessed = true;
|
||||
if (bean instanceof PostProcessedBean) {
|
||||
((PostProcessedBean) bean).postProcessed = true;
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
@@ -100,27 +115,28 @@ class BeanPostProcessorTestConfig {
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
return bean;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PostProcessorRegistrar postProcessorRegistrar() {
|
||||
return new PostProcessorRegistrar();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public PostProcessedBean postProcessedBean() {
|
||||
return new PostProcessedBean();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public SpringBeanThatWantsPostProcessedBean springBean(PostProcessedBean ppb) {
|
||||
return new SpringBeanThatWantsPostProcessedBean(ppb);
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public Module someGuiceModule() {
|
||||
return new AbstractModule() {
|
||||
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
binder().requireExplicitBindings();
|
||||
@@ -129,4 +145,5 @@ class BeanPostProcessorTestConfig {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -39,73 +39,108 @@ public class BindingAnnotationTests {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
BindingAnnotationTestsConfig.class);
|
||||
Injector injector = context.getBean(Injector.class);
|
||||
|
||||
//Check @Qualifier
|
||||
SomeDependencyWithQualifierOnProvider someDependencyWithQualifierOnClass = injector.getInstance(Key.get(SomeDependencyWithQualifierOnProvider.class, SomeQualifierAnnotation.class));
|
||||
|
||||
// Check @Qualifier
|
||||
SomeDependencyWithQualifierOnProvider someDependencyWithQualifierOnClass = injector
|
||||
.getInstance(Key.get(SomeDependencyWithQualifierOnProvider.class, SomeQualifierAnnotation.class));
|
||||
assertNotNull(someDependencyWithQualifierOnClass);
|
||||
|
||||
//Check @BindingAnnotation on Spring @Bean available in Guice
|
||||
SomeDependencyWithQualifierOnProvider someDependencyWithBindingAnnotationOnProvider = injector.getInstance(Key.get(SomeDependencyWithQualifierOnProvider.class, SomeQualifierAnnotation.class));
|
||||
|
||||
// Check @BindingAnnotation on Spring @Bean available in Guice
|
||||
SomeDependencyWithQualifierOnProvider someDependencyWithBindingAnnotationOnProvider = injector
|
||||
.getInstance(Key.get(SomeDependencyWithQualifierOnProvider.class, SomeQualifierAnnotation.class));
|
||||
assertNotNull(someDependencyWithBindingAnnotationOnProvider);
|
||||
|
||||
//Check @BindingAnnotation on Guice Binding available in Spring
|
||||
// Check @BindingAnnotation on Guice Binding available in Spring
|
||||
SomeStringHolder stringHolder = context.getBean(SomeStringHolder.class);
|
||||
assertEquals("annotated", stringHolder.annotatedString);
|
||||
assertEquals("other", stringHolder.otherAnnotatedString);
|
||||
|
||||
//Check javax @Named
|
||||
SomeDependencyWithNamedAnnotationOnProvider someDependencyWithNamedAnnotationOnProvider = injector.getInstance(Key.get(SomeDependencyWithNamedAnnotationOnProvider.class, Names.named("javaxNamed")));
|
||||
// Check javax @Named
|
||||
SomeDependencyWithNamedAnnotationOnProvider someDependencyWithNamedAnnotationOnProvider = injector
|
||||
.getInstance(Key.get(SomeDependencyWithNamedAnnotationOnProvider.class, Names.named("javaxNamed")));
|
||||
assertNotNull(someDependencyWithNamedAnnotationOnProvider);
|
||||
|
||||
//Check Guice @Named
|
||||
SomeDependencyWithGuiceNamedAnnotationOnProvider someDependencyWithGuiceNamedAnnotationOnProvider = injector.getInstance(Key.get(SomeDependencyWithGuiceNamedAnnotationOnProvider.class, Names.named("guiceNamed")));
|
||||
// Check Guice @Named
|
||||
SomeDependencyWithGuiceNamedAnnotationOnProvider someDependencyWithGuiceNamedAnnotationOnProvider = injector
|
||||
.getInstance(
|
||||
Key.get(SomeDependencyWithGuiceNamedAnnotationOnProvider.class, Names.named("guiceNamed")));
|
||||
assertNotNull(someDependencyWithGuiceNamedAnnotationOnProvider);
|
||||
|
||||
SomeDependencyWithGuiceNamedAnnotationOnProvider someSecondDependencyWithGuiceNamedAnnotationOnProvider = injector.getInstance(Key.get(SomeDependencyWithGuiceNamedAnnotationOnProvider.class, Names.named("guiceNamed2")));
|
||||
|
||||
SomeDependencyWithGuiceNamedAnnotationOnProvider someSecondDependencyWithGuiceNamedAnnotationOnProvider = injector
|
||||
.getInstance(
|
||||
Key.get(SomeDependencyWithGuiceNamedAnnotationOnProvider.class, Names.named("guiceNamed2")));
|
||||
assertNotNull(someSecondDependencyWithGuiceNamedAnnotationOnProvider);
|
||||
|
||||
//Check @Qualifier with Interface
|
||||
|
||||
// Check @Qualifier with Interface
|
||||
SomeInterface someInterface = injector.getInstance(Key.get(SomeInterface.class, SomeQualifierAnnotation.class));
|
||||
assertNotNull(someInterface);
|
||||
|
||||
//Check different types with same @Named
|
||||
|
||||
// Check different types with same @Named
|
||||
assertNotNull(injector.getInstance(SomeNamedDepWithType1.class));
|
||||
assertNotNull(injector.getInstance(SomeNamedDepWithType2.class));
|
||||
|
||||
|
||||
assertNotNull(injector.getInstance(Key.get(SomeNamedDepWithType1.class, Names.named("sameNameDifferentType"))));
|
||||
assertNotNull(injector.getInstance(Key.get(SomeNamedDepWithType2.class, Names.named("sameNameDifferentType"))));
|
||||
context.close();
|
||||
}
|
||||
|
||||
|
||||
public static class SomeDependencyWithQualifierOnProvider {}
|
||||
public static class SomeDependencyWithBindingAnnotationOnProvider {}
|
||||
public static class SomeDependencyWithNamedAnnotationOnProvider {}
|
||||
public static class SomeDependencyWithGuiceNamedAnnotationOnProvider {}
|
||||
public interface SomeInterface{}
|
||||
public static class SomeDependencyWithQualifierOnProviderWhichImplementsSomeInterface implements SomeInterface {}
|
||||
public static class SomeNamedDepWithType1 {}
|
||||
public static class SomeNamedDepWithType2 {}
|
||||
public static class SomeDependencyWithQualifierOnProvider {
|
||||
|
||||
}
|
||||
|
||||
public static class SomeDependencyWithBindingAnnotationOnProvider {
|
||||
|
||||
}
|
||||
|
||||
public static class SomeDependencyWithNamedAnnotationOnProvider {
|
||||
|
||||
}
|
||||
|
||||
public static class SomeDependencyWithGuiceNamedAnnotationOnProvider {
|
||||
|
||||
}
|
||||
|
||||
public interface SomeInterface {
|
||||
|
||||
}
|
||||
|
||||
public static class SomeDependencyWithQualifierOnProviderWhichImplementsSomeInterface implements SomeInterface {
|
||||
|
||||
}
|
||||
|
||||
public static class SomeNamedDepWithType1 {
|
||||
|
||||
}
|
||||
|
||||
public static class SomeNamedDepWithType2 {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Qualifier
|
||||
@Target({ElementType.TYPE, ElementType.METHOD})
|
||||
@Target({ ElementType.TYPE, ElementType.METHOD })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@interface SomeQualifierAnnotation {}
|
||||
@interface SomeQualifierAnnotation {
|
||||
|
||||
}
|
||||
|
||||
@BindingAnnotation
|
||||
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
|
||||
@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@interface SomeBindingAnnotation {}
|
||||
@interface SomeBindingAnnotation {
|
||||
|
||||
}
|
||||
|
||||
@BindingAnnotation
|
||||
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
|
||||
@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@interface SomeOtherBindingAnnotation {}
|
||||
@interface SomeOtherBindingAnnotation {
|
||||
|
||||
}
|
||||
|
||||
class SomeStringHolder {
|
||||
|
||||
|
||||
@Autowired
|
||||
@SomeBindingAnnotation
|
||||
public String annotatedString;
|
||||
@@ -119,55 +154,55 @@ class SomeStringHolder {
|
||||
@EnableGuiceModules
|
||||
@Configuration
|
||||
class BindingAnnotationTestsConfig {
|
||||
|
||||
|
||||
@Bean
|
||||
@SomeQualifierAnnotation
|
||||
public SomeDependencyWithQualifierOnProvider someDependencyWithQualifierOnProvider() {
|
||||
return new SomeDependencyWithQualifierOnProvider();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
@SomeBindingAnnotation
|
||||
public SomeDependencyWithBindingAnnotationOnProvider someDependencyWithBindingAnnotationOnProvider() {
|
||||
return new SomeDependencyWithBindingAnnotationOnProvider();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
@Named("javaxNamed")
|
||||
public SomeDependencyWithNamedAnnotationOnProvider someDependencyWithNamedAnnotationOnProvider() {
|
||||
return new SomeDependencyWithNamedAnnotationOnProvider();
|
||||
}
|
||||
|
||||
@Bean(name="javaxNamed2")
|
||||
|
||||
@Bean(name = "javaxNamed2")
|
||||
@Named("javaxNamed2")
|
||||
public SomeDependencyWithNamedAnnotationOnProvider someSecondDependencyWithNamedAnnotationOnProvider() {
|
||||
return new SomeDependencyWithNamedAnnotationOnProvider();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
@com.google.inject.name.Named("guiceNamed")
|
||||
public SomeDependencyWithGuiceNamedAnnotationOnProvider someDependencyWithGuiceNamedAnnotationOnProvider() {
|
||||
return new SomeDependencyWithGuiceNamedAnnotationOnProvider();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
@com.google.inject.name.Named("guiceNamed2")
|
||||
public SomeDependencyWithGuiceNamedAnnotationOnProvider someSecondDependencyWithGuiceNamedAnnotationOnProvider() {
|
||||
return new SomeDependencyWithGuiceNamedAnnotationOnProvider();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
@SomeQualifierAnnotation
|
||||
public SomeInterface someInterface() {
|
||||
return new SomeDependencyWithQualifierOnProviderWhichImplementsSomeInterface();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
@Named("sameNameDifferentType")
|
||||
public SomeNamedDepWithType1 someNamedDepWithType1() {
|
||||
return new SomeNamedDepWithType1();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
@Named("sameNameDifferentType")
|
||||
public SomeNamedDepWithType2 someNamedDepWithType2() {
|
||||
@@ -189,4 +224,5 @@ class BindingAnnotationTestsConfig {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -43,8 +43,13 @@ public class BindingDeduplicationTests {
|
||||
context.close();
|
||||
}
|
||||
|
||||
public static class SomeDependency {}
|
||||
public static class SomeOptionalDependency {}
|
||||
public static class SomeDependency {
|
||||
|
||||
}
|
||||
|
||||
public static class SomeOptionalDependency {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -68,11 +73,10 @@ class BindingDeduplicationTestsConfig {
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(SomeDependency.class).asEagerSingleton();
|
||||
OptionalBinder
|
||||
.newOptionalBinder(binder(), SomeOptionalDependency.class)
|
||||
.setDefault()
|
||||
OptionalBinder.newOptionalBinder(binder(), SomeOptionalDependency.class).setDefault()
|
||||
.to(SomeOptionalDependency.class);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -28,38 +28,54 @@ public class DuplicateNamesDifferentTypesTests {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
DuplicateNamesDifferentTypesTestsConfig.class);
|
||||
|
||||
//Check Guice @Named
|
||||
// Check Guice @Named
|
||||
assertNotNull(context.getBean(SomeNamedDepWithType1.class));
|
||||
assertNotNull(context.getBean(SomeNamedDepWithType2.class));
|
||||
assertNotNull(BeanFactoryAnnotationUtils.qualifiedBeanOfType(context.getBeanFactory(), SomeNamedDepWithType1.class, "sameNameDifferentType"));
|
||||
|
||||
//Check javax @Named
|
||||
assertNotNull(BeanFactoryAnnotationUtils.qualifiedBeanOfType(context.getBeanFactory(),
|
||||
SomeNamedDepWithType1.class, "sameNameDifferentType"));
|
||||
|
||||
// Check javax @Named
|
||||
assertNotNull(context.getBean(SomeJavaxNamedDepWithType1.class));
|
||||
assertNotNull(context.getBean(SomeJavaxNamedDepWithType2.class));
|
||||
assertNotNull(BeanFactoryAnnotationUtils.qualifiedBeanOfType(context.getBeanFactory(), SomeJavaxNamedDepWithType1.class, "sameJavaxName"));
|
||||
assertNotNull(BeanFactoryAnnotationUtils.qualifiedBeanOfType(context.getBeanFactory(),
|
||||
SomeJavaxNamedDepWithType1.class, "sameJavaxName"));
|
||||
context.getBeansOfType(SomeJavaxNamedDepWithType1.class);
|
||||
|
||||
|
||||
context.close();
|
||||
}
|
||||
|
||||
public static class SomeNamedDepWithType1 {}
|
||||
public static class SomeNamedDepWithType2 {}
|
||||
public static class SomeJavaxNamedDepWithType1 {}
|
||||
public static class SomeJavaxNamedDepWithType2 {}
|
||||
|
||||
public static class SomeClassWithDeps{
|
||||
@Autowired
|
||||
@Qualifier("sameJavaxName2")
|
||||
SomeJavaxNamedDepWithType1 qualified;
|
||||
|
||||
@Autowired
|
||||
@Named("sameJavaxName2")
|
||||
SomeJavaxNamedDepWithType1 named;
|
||||
|
||||
@Autowired
|
||||
@javax.inject.Named("sameJavaxName2")
|
||||
SomeJavaxNamedDepWithType1 javaxNamed;
|
||||
public static class SomeNamedDepWithType1 {
|
||||
|
||||
}
|
||||
|
||||
public static class SomeNamedDepWithType2 {
|
||||
|
||||
}
|
||||
|
||||
public static class SomeJavaxNamedDepWithType1 {
|
||||
|
||||
}
|
||||
|
||||
public static class SomeJavaxNamedDepWithType2 {
|
||||
|
||||
}
|
||||
|
||||
public static class SomeClassWithDeps {
|
||||
|
||||
@Autowired
|
||||
@Qualifier("sameJavaxName2")
|
||||
SomeJavaxNamedDepWithType1 qualified;
|
||||
|
||||
@Autowired
|
||||
@Named("sameJavaxName2")
|
||||
SomeJavaxNamedDepWithType1 named;
|
||||
|
||||
@Autowired
|
||||
@javax.inject.Named("sameJavaxName2")
|
||||
SomeJavaxNamedDepWithType1 javaxNamed;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@EnableGuiceModules
|
||||
@@ -76,19 +92,19 @@ class DuplicateNamesDifferentTypesTestsConfig {
|
||||
bind(SomeNamedDepWithType2.class).annotatedWith(Names.named("sameNameDifferentType"))
|
||||
.to(SomeNamedDepWithType2.class);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Named("sameJavaxName")
|
||||
|
||||
@Provides
|
||||
@Named("sameJavaxName")
|
||||
public SomeJavaxNamedDepWithType1 someJavaxNamedDepWithType1() {
|
||||
return new SomeJavaxNamedDepWithType1();
|
||||
}
|
||||
|
||||
|
||||
@Provides
|
||||
@Named("sameJavaxName")
|
||||
|
||||
@Provides
|
||||
@Named("sameJavaxName")
|
||||
public SomeJavaxNamedDepWithType2 someJavaxNamedDepWithType2() {
|
||||
return new SomeJavaxNamedDepWithType2();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -47,22 +47,23 @@ public class ElementVisitorTests {
|
||||
|
||||
@Test
|
||||
public void verifySpringModuleDoesNotBreakWhenUsingElementVisitors() {
|
||||
ElementVisitorTestSpringBean testSpringBean = context
|
||||
.getBean(ElementVisitorTestSpringBean.class);
|
||||
ElementVisitorTestSpringBean testSpringBean = context.getBean(ElementVisitorTestSpringBean.class);
|
||||
assertEquals("spring created", testSpringBean.toString());
|
||||
ElementVisitorTestGuiceBean testGuiceBean = context
|
||||
.getBean(ElementVisitorTestGuiceBean.class);
|
||||
ElementVisitorTestGuiceBean testGuiceBean = context.getBean(ElementVisitorTestGuiceBean.class);
|
||||
assertEquals("spring created", testGuiceBean.toString());
|
||||
}
|
||||
|
||||
public static class ElementVisitorTestSpringBean {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "default";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class ElementVisitorTestGuiceBean {
|
||||
|
||||
@Inject
|
||||
ElementVisitorTestSpringBean springBean;
|
||||
|
||||
@@ -70,10 +71,13 @@ public class ElementVisitorTests {
|
||||
public String toString() {
|
||||
return springBean.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class DuplicateBean {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@EnableGuiceModules
|
||||
@@ -107,8 +111,7 @@ class ElementVisitorTestConfig {
|
||||
@Override
|
||||
public Injector createInjector(List<Module> modules) {
|
||||
List<Element> elements = Elements.getElements(Stage.TOOL, modules);
|
||||
return Guice.createInjector(Stage.PRODUCTION,
|
||||
Elements.getModule(elements));
|
||||
return Guice.createInjector(Stage.PRODUCTION, Elements.getModule(elements));
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -122,4 +125,5 @@ class ElementVisitorTestConfig {
|
||||
public DuplicateBean dupeBean2() {
|
||||
return new DuplicateBean();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -34,13 +34,17 @@ public class GuiceWiringTests extends AbstractCompleteWiringTests {
|
||||
}
|
||||
|
||||
public static class TestConfig extends AbstractModule {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(Service.class).to(MyService.class);
|
||||
bind(Baz.class).in(Singleton.class);
|
||||
bind(Thang.class).annotatedWith(Names.named("thing")).to(Thang.class);
|
||||
bind(new TypeLiteral<Parameterized<String>>(){}).toInstance(new Parameterized<String>(){});
|
||||
bind(new TypeLiteral<Parameterized<String>>() {
|
||||
}).toInstance(new Parameterized<String>() {
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -20,8 +20,7 @@ public class InjectorFactoryTests {
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
Mockito.when(injectorFactory.createInjector(Mockito.anyList()))
|
||||
.thenReturn(Guice.createInjector());
|
||||
Mockito.when(injectorFactory.createInjector(Mockito.anyList())).thenReturn(Guice.createInjector());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -42,21 +41,27 @@ public class InjectorFactoryTests {
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
static class ModulesConfig {
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class InjectorFactoryConfig {
|
||||
|
||||
@Bean
|
||||
public InjectorFactory injectorFactory() {
|
||||
return injectorFactory;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class SecondInjectorFactoryConfig {
|
||||
|
||||
@Bean
|
||||
public InjectorFactory injectorFactory2() {
|
||||
return injectorFactory;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -34,10 +34,9 @@ public class JustInTimeBindingTests {
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
private Foo springGetFoo() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
ModulesConfig.class);
|
||||
context.getDefaultListableBeanFactory().registerBeanDefinition(
|
||||
Foo.class.getSimpleName(), new RootBeanDefinition(Foo.class));
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ModulesConfig.class);
|
||||
context.getDefaultListableBeanFactory().registerBeanDefinition(Foo.class.getSimpleName(),
|
||||
new RootBeanDefinition(Foo.class));
|
||||
return context.getBean(Foo.class);
|
||||
}
|
||||
|
||||
@@ -48,6 +47,7 @@ public class JustInTimeBindingTests {
|
||||
}
|
||||
|
||||
public static class Service {
|
||||
|
||||
}
|
||||
|
||||
public static class Foo {
|
||||
|
||||
@@ -14,80 +14,88 @@ import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class LazyInitializationTests {
|
||||
|
||||
@Test
|
||||
public void lazyAnnotationIsRespectedOnInjectionPointForGuiceBinding() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
context.register(TestConfig.class);
|
||||
context.register(GuiceConfig.class);
|
||||
context.refresh();
|
||||
@Test
|
||||
public void lazyAnnotationIsRespectedOnInjectionPointForGuiceBinding() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
context.register(TestConfig.class);
|
||||
context.register(GuiceConfig.class);
|
||||
context.refresh();
|
||||
|
||||
Service service = context.getBean(Service.class);
|
||||
Service service = context.getBean(Service.class);
|
||||
|
||||
assertTrue(AopUtils.isAopProxy(service.getBean()));
|
||||
assertNotNull(context.getBean(TestBean.class));
|
||||
}
|
||||
assertTrue(AopUtils.isAopProxy(service.getBean()));
|
||||
assertNotNull(context.getBean(TestBean.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lazyAnnotationIsRespectedOnInjectionPointForSpringBinding() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
context.register(TestConfig.class);
|
||||
context.register(SpringConfig.class);
|
||||
context.refresh();
|
||||
@Test
|
||||
public void lazyAnnotationIsRespectedOnInjectionPointForSpringBinding() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
context.register(TestConfig.class);
|
||||
context.register(SpringConfig.class);
|
||||
context.refresh();
|
||||
|
||||
Service service = context.getBean(Service.class);
|
||||
Service service = context.getBean(Service.class);
|
||||
|
||||
assertTrue(AopUtils.isAopProxy(service.getBean()));
|
||||
assertNotNull(context.getBean(TestBean.class));
|
||||
}
|
||||
assertTrue(AopUtils.isAopProxy(service.getBean()));
|
||||
assertNotNull(context.getBean(TestBean.class));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
static class TestConfig {
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
static class TestConfig {
|
||||
|
||||
@Bean
|
||||
public Service service(@Lazy TestBean bean) {
|
||||
return new Service(bean);
|
||||
}
|
||||
}
|
||||
@Bean
|
||||
public Service service(@Lazy TestBean bean) {
|
||||
return new Service(bean);
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class GuiceConfig {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public GuiceModule guiceModule() {
|
||||
return new GuiceModule();
|
||||
}
|
||||
}
|
||||
@Configuration
|
||||
static class GuiceConfig {
|
||||
|
||||
@Configuration
|
||||
static class SpringConfig {
|
||||
@Bean
|
||||
public GuiceModule guiceModule() {
|
||||
return new GuiceModule();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public TestBean testBean() {
|
||||
return new TestBean();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static class GuiceModule extends AbstractModule {
|
||||
@Configuration
|
||||
static class SpringConfig {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(TestBean.class).asEagerSingleton();
|
||||
}
|
||||
}
|
||||
@Bean
|
||||
public TestBean testBean() {
|
||||
return new TestBean();
|
||||
}
|
||||
|
||||
static class Service {
|
||||
private final TestBean bean;
|
||||
}
|
||||
|
||||
public Service(TestBean bean) {
|
||||
this.bean = bean;
|
||||
}
|
||||
static class GuiceModule extends AbstractModule {
|
||||
|
||||
public TestBean getBean() {
|
||||
return bean;
|
||||
}
|
||||
}
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(TestBean.class).asEagerSingleton();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class Service {
|
||||
|
||||
private final TestBean bean;
|
||||
|
||||
public Service(TestBean bean) {
|
||||
this.bean = bean;
|
||||
}
|
||||
|
||||
public TestBean getBean() {
|
||||
return bean;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class TestBean {
|
||||
|
||||
}
|
||||
|
||||
static class TestBean {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,22 +23,25 @@ public class MapWiringTests {
|
||||
@SuppressWarnings({ "resource", "unused" })
|
||||
@Test
|
||||
public void testProvidesMap() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
ModulesConfig.class, FooBar.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ModulesConfig.class,
|
||||
FooBar.class);
|
||||
Bar bar = context.getBean(Bar.class);
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
static class ModulesConfig {
|
||||
|
||||
@Bean
|
||||
TestConfig testConfig() {
|
||||
return new TestConfig();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class FooBar {
|
||||
|
||||
@Bean
|
||||
Bar foo(Map<String, Foo> foos) {
|
||||
assertTrue(!foos.isEmpty());
|
||||
@@ -48,16 +51,20 @@ public class MapWiringTests {
|
||||
}
|
||||
|
||||
static class TestConfig extends AbstractModule {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(Foo.class);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class Foo {
|
||||
|
||||
}
|
||||
|
||||
static class Bar {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -48,20 +48,26 @@ public class ModuleFilteringTests {
|
||||
}
|
||||
|
||||
public static interface SomeInterface {
|
||||
|
||||
}
|
||||
|
||||
public static class SomeDependency implements SomeInterface {
|
||||
|
||||
public SomeDependency() {
|
||||
throw new RuntimeException("Should never be instantiated");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class FilterThisModule extends AbstractModule {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(SomeInterface.class).to(SomeDependency.class).asEagerSingleton();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@EnableGuiceModules
|
||||
@@ -83,4 +89,5 @@ class ModuleFilteringTestsConfig {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -44,11 +44,16 @@ public class NativeGuiceTests {
|
||||
}
|
||||
|
||||
public static class TestConfig extends AbstractModule {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(Foo.class).annotatedWith(Names.named("bar")).to(Foo.class);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class Foo {
|
||||
|
||||
}
|
||||
|
||||
public static class Foo {}
|
||||
}
|
||||
|
||||
@@ -26,23 +26,24 @@ import com.google.inject.name.Names;
|
||||
public class PrivateModuleTests {
|
||||
|
||||
private static AnnotationConfigApplicationContext context;
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void init() {
|
||||
context = new AnnotationConfigApplicationContext(PrivateModuleTestConfig.class);
|
||||
}
|
||||
|
||||
|
||||
@AfterClass
|
||||
public static void cleanup() {
|
||||
if(context != null) {
|
||||
if (context != null) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void verifyPrivateModulesCanExposeBindings() {
|
||||
public void verifyPrivateModulesCanExposeBindings() {
|
||||
Injector injector = context.getBean(Injector.class);
|
||||
SomeInterface injectorProvidedPrivateBinding = injector.getInstance(Key.get(SomeInterface.class, Names.named("exposed")));
|
||||
SomeInterface injectorProvidedPrivateBinding = injector
|
||||
.getInstance(Key.get(SomeInterface.class, Names.named("exposed")));
|
||||
assertNotNull(injectorProvidedPrivateBinding);
|
||||
SomeInterface springProvidedPrivateBinding = context.getBean(SomeInterface.class);
|
||||
assertNotNull(springProvidedPrivateBinding);
|
||||
@@ -55,45 +56,55 @@ public class PrivateModuleTests {
|
||||
assertNotNull(beanDependingOnPrivateBinding);
|
||||
assertEquals("foo", beanDependingOnPrivateBinding);
|
||||
}
|
||||
|
||||
@Test(expected=ConfigurationException.class)
|
||||
|
||||
@Test(expected = ConfigurationException.class)
|
||||
public void verifyPrivateModulesPrivateBindingsAreNotExposedViaInjector() {
|
||||
Injector injector = context.getBean(Injector.class);
|
||||
injector.getInstance(Key.get(SomeInterface.class, Names.named("notexposed")));
|
||||
}
|
||||
|
||||
@Test(expected=NoSuchBeanDefinitionException.class)
|
||||
|
||||
@Test(expected = NoSuchBeanDefinitionException.class)
|
||||
public void verifyPrivateModulesPrivateBindingsAreNotExposedViaSpring() {
|
||||
context.getBean("notexposed",SomeInterface.class);
|
||||
context.getBean("notexposed", SomeInterface.class);
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = NoSuchBeanDefinitionException.class)
|
||||
public void verifyPrivateModulesPrivateBindingsAreNotExposedViaSpringWithQualifier() {
|
||||
BeanFactoryAnnotationUtils.qualifiedBeanOfType(context.getBeanFactory(), SomeInterface.class, "notexposed");
|
||||
}
|
||||
|
||||
public static interface SomeInterface {}
|
||||
public static class SomePrivateBinding implements SomeInterface {}
|
||||
|
||||
public static interface SomeInterface {
|
||||
|
||||
}
|
||||
|
||||
public static class SomePrivateBinding implements SomeInterface {
|
||||
|
||||
}
|
||||
|
||||
public static class SomePrivateModule extends PrivateModule {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(SomeInterface.class).annotatedWith(Names.named("exposed")).to(SomePrivateBinding.class).asEagerSingleton();
|
||||
bind(SomeInterface.class).annotatedWith(Names.named("notexposed")).to(SomePrivateBinding.class).asEagerSingleton();
|
||||
expose(SomeInterface.class).annotatedWith(Names.named("exposed"));
|
||||
bind(SomeInterface.class).annotatedWith(Names.named("exposed")).to(SomePrivateBinding.class)
|
||||
.asEagerSingleton();
|
||||
bind(SomeInterface.class).annotatedWith(Names.named("notexposed")).to(SomePrivateBinding.class)
|
||||
.asEagerSingleton();
|
||||
expose(SomeInterface.class).annotatedWith(Names.named("exposed"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@EnableGuiceModules
|
||||
@Configuration
|
||||
class PrivateModuleTestConfig {
|
||||
|
||||
|
||||
@Bean
|
||||
public String somethingThatWantsAPrivateBinding(SomeInterface privateBinding) {
|
||||
return "foo";
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public Module module() {
|
||||
return new AbstractModule() {
|
||||
@@ -103,4 +114,5 @@ class PrivateModuleTestConfig {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -13,45 +13,56 @@ import static org.junit.Assert.*;
|
||||
|
||||
public class PrototypeScopedBeanTests {
|
||||
|
||||
@Test
|
||||
public void testPrototypeScopedBeans() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
ModulesConfig.class);
|
||||
Injector injector = context.getBean(Injector.class);
|
||||
GuiceService1 gs1 = injector.getInstance(GuiceService1.class);
|
||||
GuiceService2 gs2 = injector.getInstance((GuiceService2.class));
|
||||
assertNotNull(gs1);
|
||||
assertNotNull(gs2);
|
||||
assertNotEquals(gs1.bean, gs2.bean);
|
||||
}
|
||||
@Test
|
||||
public void testPrototypeScopedBeans() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ModulesConfig.class);
|
||||
Injector injector = context.getBean(Injector.class);
|
||||
GuiceService1 gs1 = injector.getInstance(GuiceService1.class);
|
||||
GuiceService2 gs2 = injector.getInstance((GuiceService2.class));
|
||||
assertNotNull(gs1);
|
||||
assertNotNull(gs2);
|
||||
assertNotEquals(gs1.bean, gs2.bean);
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
static class ModulesConfig {
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
static class ModulesConfig {
|
||||
|
||||
@Bean
|
||||
public Module guiceModule() {
|
||||
return new AbstractModule() {
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(GuiceService1.class).asEagerSingleton();
|
||||
bind(GuiceService2.class).asEagerSingleton();
|
||||
}
|
||||
};
|
||||
}
|
||||
@Bean
|
||||
public Module guiceModule() {
|
||||
return new AbstractModule() {
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(GuiceService1.class).asEagerSingleton();
|
||||
bind(GuiceService2.class).asEagerSingleton();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Scope("prototype")
|
||||
public PrototypeBean prototypeBean() {
|
||||
return new PrototypeBean();
|
||||
}
|
||||
}
|
||||
@Bean
|
||||
@Scope("prototype")
|
||||
public PrototypeBean prototypeBean() {
|
||||
return new PrototypeBean();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class PrototypeBean {
|
||||
|
||||
}
|
||||
|
||||
public static class GuiceService1 {
|
||||
|
||||
@Inject
|
||||
PrototypeBean bean;
|
||||
|
||||
}
|
||||
|
||||
public static class GuiceService2 {
|
||||
|
||||
@Inject
|
||||
PrototypeBean bean;
|
||||
|
||||
}
|
||||
|
||||
public static class PrototypeBean {}
|
||||
public static class GuiceService1 {
|
||||
@Inject PrototypeBean bean;
|
||||
}
|
||||
public static class GuiceService2 {
|
||||
@Inject PrototypeBean bean;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,8 +28,8 @@ public class ProvidesSupplierWiringTests {
|
||||
@SuppressWarnings({ "resource", "unused" })
|
||||
@Test
|
||||
public void testProvidesSupplier() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
ModulesConfig.class, FooBar.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ModulesConfig.class,
|
||||
FooBar.class);
|
||||
Foo foo = context.getBean(Foo.class);
|
||||
Bar bar = context.getBean(Bar.class);
|
||||
}
|
||||
@@ -37,14 +37,17 @@ public class ProvidesSupplierWiringTests {
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
static class ModulesConfig {
|
||||
|
||||
@Bean
|
||||
TestConfig testConfig() {
|
||||
return new TestConfig();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class FooBar {
|
||||
|
||||
@Bean
|
||||
Foo foo(Supplier<Foo> supplier) {
|
||||
return supplier.get();
|
||||
@@ -54,9 +57,11 @@ public class ProvidesSupplierWiringTests {
|
||||
Bar bar(Supplier<Bar> supplier) {
|
||||
return supplier.get();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class TestConfig extends AbstractModule {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
}
|
||||
@@ -72,9 +77,11 @@ public class ProvidesSupplierWiringTests {
|
||||
Supplier<Bar> getBar() {
|
||||
return () -> new Bar();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class Foo {
|
||||
|
||||
}
|
||||
|
||||
static class Bar {
|
||||
@@ -88,19 +95,17 @@ public class ProvidesSupplierWiringTests {
|
||||
@Ignore
|
||||
@Test
|
||||
public void testProvidesSupplierSpring() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
FooBarSpring.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(FooBarSpring.class);
|
||||
SpringInjector injector = new SpringInjector(context);
|
||||
Foo_Spring fooSpring = injector
|
||||
.getInstance(Key.get(new TypeLiteral<Supplier<Foo_Spring>>() {
|
||||
})).get();
|
||||
Bar_Spring barSpring = injector
|
||||
.getInstance(Key.get(new TypeLiteral<Supplier<Bar_Spring>>() {
|
||||
})).get();
|
||||
Foo_Spring fooSpring = injector.getInstance(Key.get(new TypeLiteral<Supplier<Foo_Spring>>() {
|
||||
})).get();
|
||||
Bar_Spring barSpring = injector.getInstance(Key.get(new TypeLiteral<Supplier<Bar_Spring>>() {
|
||||
})).get();
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class FooBarSpring {
|
||||
|
||||
@Bean
|
||||
Supplier<Foo_Spring> fooSpring() {
|
||||
return () -> new Foo_Spring();
|
||||
@@ -110,9 +115,11 @@ public class ProvidesSupplierWiringTests {
|
||||
Bar_Spring barSpring() {
|
||||
return new Bar_Spring();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class Foo_Spring {
|
||||
|
||||
}
|
||||
|
||||
static class Bar_Spring {
|
||||
|
||||
@@ -24,25 +24,24 @@ public class ScopingTests {
|
||||
|
||||
@Test
|
||||
public void verifyScopes() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
ScopingTestsConfig.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopingTestsConfig.class);
|
||||
SomeSingletonDependency someSingletonDependency1 = context.getBean(SomeSingletonDependency.class);
|
||||
SomeSingletonDependency someSingletonDependency2 = context.getBean(SomeSingletonDependency.class);
|
||||
|
||||
|
||||
assertNotNull(someSingletonDependency1);
|
||||
assertNotNull(someSingletonDependency2);
|
||||
assertEquals(someSingletonDependency1, someSingletonDependency2);
|
||||
|
||||
|
||||
SomeNoScopeDependency someNoScopeDependency1 = context.getBean(SomeNoScopeDependency.class);
|
||||
SomeNoScopeDependency someNoScopeDependency2 = context.getBean(SomeNoScopeDependency.class);
|
||||
|
||||
|
||||
assertNotNull(someNoScopeDependency1);
|
||||
assertNotNull(someNoScopeDependency2);
|
||||
assertNotEquals(someNoScopeDependency1, someNoScopeDependency2);
|
||||
|
||||
|
||||
SomeCustomScopeDependency someCustomScopeDependency1 = context.getBean(SomeCustomScopeDependency.class);
|
||||
SomeCustomScopeDependency someCustomScopeDependency2 = context.getBean(SomeCustomScopeDependency.class);
|
||||
|
||||
|
||||
assertNotNull(someCustomScopeDependency1);
|
||||
assertNotNull(someCustomScopeDependency2);
|
||||
assertNotEquals(someCustomScopeDependency1, someCustomScopeDependency2);
|
||||
@@ -52,16 +51,30 @@ public class ScopingTests {
|
||||
context.close();
|
||||
}
|
||||
|
||||
public static class SomeSingletonDependency {}
|
||||
public static class SomeNoScopeDependency {}
|
||||
public static class SomeCustomScopeDependency {
|
||||
String value;
|
||||
public SomeCustomScopeDependency() {}
|
||||
public SomeCustomScopeDependency(String value) {
|
||||
this.value=value;
|
||||
}
|
||||
public static class SomeSingletonDependency {
|
||||
|
||||
}
|
||||
|
||||
public static class SomeNoScopeDependency {
|
||||
|
||||
}
|
||||
|
||||
public static class SomeCustomScopeDependency {
|
||||
|
||||
String value;
|
||||
|
||||
public SomeCustomScopeDependency() {
|
||||
}
|
||||
|
||||
public SomeCustomScopeDependency(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public interface CustomScope extends Scope {
|
||||
|
||||
}
|
||||
public interface CustomScope extends Scope {}
|
||||
|
||||
}
|
||||
|
||||
@@ -74,17 +87,19 @@ class ScopingTestsConfig {
|
||||
return new AbstractModule() {
|
||||
@Override
|
||||
protected void configure() {
|
||||
CustomScope customScope = new CustomScope(){
|
||||
CustomScope customScope = new CustomScope() {
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) {
|
||||
Provider<?> provider = () -> new SomeCustomScopeDependency("custom");
|
||||
return (Provider<T>) provider;
|
||||
}};
|
||||
}
|
||||
};
|
||||
bind(SomeSingletonDependency.class).asEagerSingleton();
|
||||
bind(SomeNoScopeDependency.class);
|
||||
bind(SomeCustomScopeDependency.class).in(customScope);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
@@ -26,14 +26,17 @@ public class SimpleWiringTests {
|
||||
@Test
|
||||
public void springyFoo() {
|
||||
@SuppressWarnings("resource")
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class, MyService.class);
|
||||
context.getDefaultListableBeanFactory().registerBeanDefinition(Foo.class.getSimpleName(), new RootBeanDefinition(Foo.class));
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class,
|
||||
MyService.class);
|
||||
context.getDefaultListableBeanFactory().registerBeanDefinition(Foo.class.getSimpleName(),
|
||||
new RootBeanDefinition(Foo.class));
|
||||
assertNotNull(context.getBean(Foo.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hybridFoo() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class, ModulesConfig.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class,
|
||||
ModulesConfig.class);
|
||||
Injector app = new SpringInjector(context);
|
||||
assertNotNull(app.getInstance(Foo.class));
|
||||
}
|
||||
@@ -41,23 +44,28 @@ public class SimpleWiringTests {
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
static class ModulesConfig {
|
||||
|
||||
}
|
||||
|
||||
public static class TestConfig extends AbstractModule {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(Service.class).to(MyService.class);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
interface Service {
|
||||
|
||||
interface Service {
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static class MyService implements Service {
|
||||
|
||||
}
|
||||
|
||||
public static class Foo {
|
||||
|
||||
|
||||
@Inject
|
||||
public Foo(Service service) {
|
||||
}
|
||||
|
||||
@@ -15,61 +15,70 @@ import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class SpringAutowiredCollectionTests {
|
||||
|
||||
@Test
|
||||
public void getAutowiredCollection() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
context.register(TestConfig.class);
|
||||
context.refresh();
|
||||
Injector injector = new SpringInjector(context);
|
||||
@Test
|
||||
public void getAutowiredCollection() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
|
||||
context.register(TestConfig.class);
|
||||
context.refresh();
|
||||
Injector injector = new SpringInjector(context);
|
||||
|
||||
ServicesHolder servicesHolder = injector.getInstance(ServicesHolder.class);
|
||||
ServicesHolder servicesHolder = injector.getInstance(ServicesHolder.class);
|
||||
|
||||
assertEquals(2, servicesHolder.existingServices.size());
|
||||
assertEquals(0, servicesHolder.nonExistingServices.size());
|
||||
}
|
||||
assertEquals(2, servicesHolder.existingServices.size());
|
||||
assertEquals(0, servicesHolder.nonExistingServices.size());
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
static class TestConfig {
|
||||
@Bean
|
||||
public ServicesHolder serviceHolder(Map<String, Service> existingServices,
|
||||
Map<String, NonExistingService> nonExistingServices) {
|
||||
return new ServicesHolder(existingServices, nonExistingServices);
|
||||
}
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
static class TestConfig {
|
||||
|
||||
@Bean
|
||||
public Service service() {
|
||||
return new Service();
|
||||
}
|
||||
@Bean
|
||||
public ServicesHolder serviceHolder(Map<String, Service> existingServices,
|
||||
Map<String, NonExistingService> nonExistingServices) {
|
||||
return new ServicesHolder(existingServices, nonExistingServices);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public GuiceModule guiceServiceModule() {
|
||||
return new GuiceModule();
|
||||
}
|
||||
}
|
||||
@Bean
|
||||
public Service service() {
|
||||
return new Service();
|
||||
}
|
||||
|
||||
static class Service {
|
||||
}
|
||||
@Bean
|
||||
public GuiceModule guiceServiceModule() {
|
||||
return new GuiceModule();
|
||||
}
|
||||
|
||||
static class NonExistingService {
|
||||
}
|
||||
}
|
||||
|
||||
static class GuiceModule extends AbstractModule {
|
||||
static class Service {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(Service.class).asEagerSingleton();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static class ServicesHolder {
|
||||
final Map<String, Service> existingServices;
|
||||
final Map<String, NonExistingService> nonExistingServices;
|
||||
static class NonExistingService {
|
||||
|
||||
}
|
||||
|
||||
static class GuiceModule extends AbstractModule {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
bind(Service.class).asEagerSingleton();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class ServicesHolder {
|
||||
|
||||
final Map<String, Service> existingServices;
|
||||
|
||||
final Map<String, NonExistingService> nonExistingServices;
|
||||
|
||||
public ServicesHolder(Map<String, Service> existingServices,
|
||||
Map<String, NonExistingService> nonExistingServices) {
|
||||
this.existingServices = existingServices;
|
||||
this.nonExistingServices = nonExistingServices;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public ServicesHolder(Map<String, Service> existingServices,
|
||||
Map<String, NonExistingService> nonExistingServices) {
|
||||
this.existingServices = existingServices;
|
||||
this.nonExistingServices = nonExistingServices;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,8 +38,7 @@ public class SuperClassTests {
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
private void baseTestSpringInterface(Class<?> configClass) {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
configClass);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClass);
|
||||
assertTrue(context.getBean(IParent.class) instanceof IGrandChildImpl);
|
||||
assertTrue(context.getBean(IChild.class) instanceof IGrandChildImpl);
|
||||
assertTrue(context.getBean(IGrandChild.class) instanceof IGrandChildImpl);
|
||||
@@ -62,8 +61,7 @@ public class SuperClassTests {
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
private void baseTestGuiceInterface(Class<?> configClass) {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
configClass);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClass);
|
||||
Injector injector = context.getBean(Injector.class);
|
||||
assertTrue(injector.getInstance(IParent.class) instanceof IGrandChildImpl);
|
||||
assertTrue(injector.getInstance(IChild.class) instanceof IGrandChildImpl);
|
||||
@@ -87,20 +85,19 @@ public class SuperClassTests {
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
private void baseTestSpringInterfaceWithType(Class<?> configClass) {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
configClass);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClass);
|
||||
|
||||
String[] allParentBeanNames = context.getBeanNamesForType(IParentWithType.class);
|
||||
assertEquals(2, allParentBeanNames.length);
|
||||
|
||||
String[] stringParentBeanNames = context.getBeanNamesForType(
|
||||
ResolvableType.forClassWithGenerics(IParentWithType.class, String.class));
|
||||
String[] stringParentBeanNames = context
|
||||
.getBeanNamesForType(ResolvableType.forClassWithGenerics(IParentWithType.class, String.class));
|
||||
assertEquals(1, stringParentBeanNames.length);
|
||||
assertTrue(new TypeLiteral<IGrandChildWithType<String>>() {
|
||||
}.getRawType().isInstance(context.getBean(stringParentBeanNames[0])));
|
||||
|
||||
String[] integerParentBeanNames = context.getBeanNamesForType(ResolvableType
|
||||
.forClassWithGenerics(IParentWithType.class, Integer.class));
|
||||
String[] integerParentBeanNames = context
|
||||
.getBeanNamesForType(ResolvableType.forClassWithGenerics(IParentWithType.class, Integer.class));
|
||||
assertEquals(1, integerParentBeanNames.length);
|
||||
assertTrue(new TypeLiteral<IGrandChildWithType<Integer>>() {
|
||||
}.getRawType().isInstance(context.getBean(integerParentBeanNames[0])));
|
||||
@@ -108,30 +105,29 @@ public class SuperClassTests {
|
||||
String[] allChildBeanNames = context.getBeanNamesForType(IChildWithType.class);
|
||||
assertEquals(2, allChildBeanNames.length);
|
||||
|
||||
String[] stringChildBeanNames = context.getBeanNamesForType(
|
||||
ResolvableType.forClassWithGenerics(IChildWithType.class, String.class));
|
||||
String[] stringChildBeanNames = context
|
||||
.getBeanNamesForType(ResolvableType.forClassWithGenerics(IChildWithType.class, String.class));
|
||||
assertEquals(1, stringChildBeanNames.length);
|
||||
assertTrue(new TypeLiteral<IChildWithType<String>>() {
|
||||
}.getRawType().isInstance(context.getBean(stringChildBeanNames[0])));
|
||||
|
||||
String[] integerChildBeanNames = context.getBeanNamesForType(
|
||||
ResolvableType.forClassWithGenerics(IChildWithType.class, Integer.class));
|
||||
String[] integerChildBeanNames = context
|
||||
.getBeanNamesForType(ResolvableType.forClassWithGenerics(IChildWithType.class, Integer.class));
|
||||
assertEquals(1, integerChildBeanNames.length);
|
||||
assertTrue(new TypeLiteral<IChildWithType<Integer>>() {
|
||||
}.getRawType().isInstance(context.getBean(integerChildBeanNames[0])));
|
||||
|
||||
String[] allGrandChildBeanNames = context
|
||||
.getBeanNamesForType(IGrandChildWithType.class);
|
||||
String[] allGrandChildBeanNames = context.getBeanNamesForType(IGrandChildWithType.class);
|
||||
assertEquals(2, allGrandChildBeanNames.length);
|
||||
|
||||
String[] stringGrandChildBeanNames = context.getBeanNamesForType(ResolvableType
|
||||
.forClassWithGenerics(IGrandChildWithType.class, String.class));
|
||||
String[] stringGrandChildBeanNames = context
|
||||
.getBeanNamesForType(ResolvableType.forClassWithGenerics(IGrandChildWithType.class, String.class));
|
||||
assertEquals(1, stringGrandChildBeanNames.length);
|
||||
assertTrue(new TypeLiteral<IGrandChildWithType<String>>() {
|
||||
}.getRawType().isInstance(context.getBean(stringGrandChildBeanNames[0])));
|
||||
|
||||
String[] integerGrandChildBeanNames = context.getBeanNamesForType(ResolvableType
|
||||
.forClassWithGenerics(IGrandChildWithType.class, Integer.class));
|
||||
String[] integerGrandChildBeanNames = context
|
||||
.getBeanNamesForType(ResolvableType.forClassWithGenerics(IGrandChildWithType.class, Integer.class));
|
||||
assertEquals(1, integerGrandChildBeanNames.length);
|
||||
assertTrue(new TypeLiteral<IGrandChildWithType<Integer>>() {
|
||||
}.getRawType().isInstance(context.getBean(integerGrandChildBeanNames[0])));
|
||||
@@ -155,8 +151,7 @@ public class SuperClassTests {
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
private void baseTestGuiceInterfaceWithType(Class<?> configClass) {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
configClass);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClass);
|
||||
Injector injector = context.getBean(Injector.class);
|
||||
IParentWithType<String> iParentString = injector
|
||||
.getInstance(Key.get(new TypeLiteral<IParentWithType<String>>() {
|
||||
@@ -167,9 +162,8 @@ public class SuperClassTests {
|
||||
}));
|
||||
assertTrue(iParentInteger instanceof IGrandChildInteger);
|
||||
|
||||
IChildWithType<String> iChildString = injector
|
||||
.getInstance(Key.get(new TypeLiteral<IChildWithType<String>>() {
|
||||
}));
|
||||
IChildWithType<String> iChildString = injector.getInstance(Key.get(new TypeLiteral<IChildWithType<String>>() {
|
||||
}));
|
||||
assertTrue(iChildString instanceof IGrandChildString);
|
||||
IChildWithType<Integer> iChildInteger = injector
|
||||
.getInstance(Key.get(new TypeLiteral<IChildWithType<Integer>>() {
|
||||
@@ -189,8 +183,7 @@ public class SuperClassTests {
|
||||
@SuppressWarnings("resource")
|
||||
@Test
|
||||
public void testSpringClass() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
ModulesConfig.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ModulesConfig.class);
|
||||
IFoo iFoo = context.getBean(IFoo.class);
|
||||
assertTrue(iFoo instanceof Foo);
|
||||
assertTrue(iFoo instanceof SubFoo);
|
||||
@@ -216,8 +209,7 @@ public class SuperClassTests {
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
private void baseTestGuiceClass(Class<?> configClass) {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
configClass);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClass);
|
||||
Injector injector = context.getBean(Injector.class);
|
||||
IFoo iFoo = injector.getInstance(IFoo.class);
|
||||
assertTrue(iFoo instanceof Foo);
|
||||
@@ -244,10 +236,9 @@ public class SuperClassTests {
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
private void baseTestSpringClassWithType(Class<?> configClass) {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
configClass);
|
||||
String[] stringBeanNames = context.getBeanNamesForType(
|
||||
ResolvableType.forClassWithGenerics(IFooWithType.class, String.class));
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClass);
|
||||
String[] stringBeanNames = context
|
||||
.getBeanNamesForType(ResolvableType.forClassWithGenerics(IFooWithType.class, String.class));
|
||||
assertEquals(1, stringBeanNames.length);
|
||||
assertTrue(context.getBean(stringBeanNames[0]) instanceof StringFoo);
|
||||
assertTrue(context.getBean(stringBeanNames[0]) instanceof SubStringFoo);
|
||||
@@ -257,8 +248,8 @@ public class SuperClassTests {
|
||||
assertTrue(context.getBean(stringBeanNames[0]) instanceof StringFoo);
|
||||
assertTrue(context.getBean(stringBeanNames[0]) instanceof SubStringFoo);
|
||||
|
||||
String[] integerBeanNames = context.getBeanNamesForType(
|
||||
ResolvableType.forClassWithGenerics(IFooWithType.class, Integer.class));
|
||||
String[] integerBeanNames = context
|
||||
.getBeanNamesForType(ResolvableType.forClassWithGenerics(IFooWithType.class, Integer.class));
|
||||
assertEquals(1, integerBeanNames.length);
|
||||
assertTrue(context.getBean(integerBeanNames[0]) instanceof IntegerFoo);
|
||||
assertTrue(context.getBean(integerBeanNames[0]) instanceof SubIntegerFoo);
|
||||
@@ -286,13 +277,11 @@ public class SuperClassTests {
|
||||
|
||||
@SuppressWarnings("resource")
|
||||
private void baseTestGuiceClassWithType(Class<?> configClass) {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
configClass);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClass);
|
||||
Injector injector = context.getBean(Injector.class);
|
||||
|
||||
IFooWithType<String> iFooWithTypeString = injector
|
||||
.getInstance(Key.get(new TypeLiteral<IFooWithType<String>>() {
|
||||
}));
|
||||
IFooWithType<String> iFooWithTypeString = injector.getInstance(Key.get(new TypeLiteral<IFooWithType<String>>() {
|
||||
}));
|
||||
assertTrue(iFooWithTypeString instanceof StringFoo);
|
||||
assertTrue(iFooWithTypeString instanceof SubStringFoo);
|
||||
|
||||
@@ -326,8 +315,7 @@ public class SuperClassTests {
|
||||
|
||||
private void baseTestSpringFactoryBean(Class<?> configClass) {
|
||||
@SuppressWarnings("resource")
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
configClass);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClass);
|
||||
|
||||
Bar bar = context.getBean(Bar.class);
|
||||
assertTrue(bar instanceof Bar);
|
||||
@@ -349,14 +337,14 @@ public class SuperClassTests {
|
||||
}
|
||||
|
||||
private void baseTestGuiceFactoryBean(Class<?> configClass) {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
configClass);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClass);
|
||||
Injector injector = context.getBean(Injector.class);
|
||||
Bar bar = injector.getInstance(Bar.class);
|
||||
assertTrue(bar instanceof Bar);
|
||||
}
|
||||
|
||||
static class DisableJITConfig {
|
||||
|
||||
@Bean
|
||||
public AbstractModule disableJITModule() {
|
||||
return new AbstractModule() {
|
||||
@@ -366,6 +354,7 @@ public class SuperClassTests {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -411,19 +400,22 @@ public class SuperClassTests {
|
||||
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
@Import({ IGrandChildImpl.class, IGrandChildString.class, IGrandChildInteger.class,
|
||||
SubFoo.class, SubStringFoo.class, SubIntegerFoo.class, BarFactory.class })
|
||||
@Import({ IGrandChildImpl.class, IGrandChildString.class, IGrandChildInteger.class, SubFoo.class,
|
||||
SubStringFoo.class, SubIntegerFoo.class, BarFactory.class })
|
||||
static class ImportConfig extends DisableJITConfig {
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
@ComponentScan(basePackageClasses = ComponentScanConfig.class, resourcePattern = "**/SuperClassTests**.class", excludeFilters = {
|
||||
@ComponentScan.Filter(Configuration.class) })
|
||||
@ComponentScan(basePackageClasses = ComponentScanConfig.class, resourcePattern = "**/SuperClassTests**.class",
|
||||
excludeFilters = { @ComponentScan.Filter(Configuration.class) })
|
||||
static class ComponentScanConfig extends DisableJITConfig {
|
||||
|
||||
}
|
||||
|
||||
public interface IParent {
|
||||
|
||||
}
|
||||
|
||||
public interface IChild extends IParent {
|
||||
@@ -497,6 +489,7 @@ public class SuperClassTests {
|
||||
}
|
||||
|
||||
public static class Bar {
|
||||
|
||||
}
|
||||
|
||||
@Component
|
||||
@@ -511,5 +504,7 @@ public class SuperClassTests {
|
||||
public Class<?> getObjectType() {
|
||||
return Bar.class;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -43,36 +43,32 @@ public class EnableGuiceModulesTests {
|
||||
public void cleanUp() {
|
||||
System.clearProperty("spring.guice.dedup");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void test() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
TestConfig.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
|
||||
assertNotNull(context.getBean(Foo.class));
|
||||
context.close();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testWithDedupFeatureEnabled() {
|
||||
System.setProperty("spring.guice.dedup", "true");
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
TestConfig.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
|
||||
assertNotNull(context.getBean(Foo.class));
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void module() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
ModuleConfig.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ModuleConfig.class);
|
||||
assertNotNull(context.getBean(Foo.class));
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void moduleBean() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
ModuleBeanConfig.class);
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ModuleBeanConfig.class);
|
||||
assertNotNull(context.getBean(Foo.class));
|
||||
context.close();
|
||||
}
|
||||
@@ -85,9 +81,11 @@ public class EnableGuiceModulesTests {
|
||||
}
|
||||
|
||||
interface Service {
|
||||
|
||||
}
|
||||
|
||||
protected static class MyService implements Service {
|
||||
|
||||
}
|
||||
|
||||
public static class Foo {
|
||||
@@ -96,6 +94,7 @@ public class EnableGuiceModulesTests {
|
||||
public Foo(@Named("service") Service service) {
|
||||
service.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -160,11 +159,14 @@ public class EnableGuiceModulesTests {
|
||||
}
|
||||
|
||||
public static class SpringProvidedBean {
|
||||
|
||||
public SpringProvidedBean(GuiceProvidedBean guiceProvidedBean) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class GuiceProvidedBean {
|
||||
|
||||
}
|
||||
|
||||
public static class GuiceService {
|
||||
@@ -172,6 +174,7 @@ public class EnableGuiceModulesTests {
|
||||
@Inject
|
||||
public GuiceService(SpringProvidedBean springProvidedBean) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class MyGuiceModule extends AbstractModule {
|
||||
|
||||
@@ -22,37 +22,44 @@ import org.springframework.context.annotation.Configuration;
|
||||
|
||||
public class GuiceModuleAnnotationGenericTypeTests {
|
||||
|
||||
public interface Foo<T> {
|
||||
T getValue();
|
||||
}
|
||||
public interface Foo<T> {
|
||||
|
||||
public static class FooImpl<T> implements Foo<T> {
|
||||
private final T payload;
|
||||
T getValue();
|
||||
|
||||
FooImpl(T payload) {
|
||||
this.payload = payload;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getValue() {
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
public static class FooImpl<T> implements Foo<T> {
|
||||
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
@GuiceModule
|
||||
static class TestConfig {
|
||||
@Bean
|
||||
public FooImpl<String> fooBean() {
|
||||
return new FooImpl<String>("foo.foo.foo");
|
||||
}
|
||||
}
|
||||
private final T payload;
|
||||
|
||||
@Test
|
||||
public void testBinding() {
|
||||
FooImpl(T payload) {
|
||||
this.payload = payload;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getValue() {
|
||||
return payload;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
@GuiceModule
|
||||
static class TestConfig {
|
||||
|
||||
@Bean
|
||||
public FooImpl<String> fooBean() {
|
||||
return new FooImpl<String>("foo.foo.foo");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBinding() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
|
||||
assertNotNull(context.getBean(Foo.class));
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -82,7 +82,8 @@ public class GuiceModuleAnnotationTests {
|
||||
|
||||
@Test
|
||||
public void twoIncludes() throws Exception {
|
||||
Injector injector = createInjector(TestConfig.class, MetadataIncludesConfig.class, MetadataMoreIncludesConfig.class);
|
||||
Injector injector = createInjector(TestConfig.class, MetadataIncludesConfig.class,
|
||||
MetadataMoreIncludesConfig.class);
|
||||
assertNotNull(injector.getBinding(Service.class));
|
||||
}
|
||||
|
||||
@@ -92,9 +93,11 @@ public class GuiceModuleAnnotationTests {
|
||||
}
|
||||
|
||||
interface Service {
|
||||
|
||||
}
|
||||
|
||||
protected static class MyService implements Service {
|
||||
|
||||
}
|
||||
|
||||
public static class Foo {
|
||||
@@ -106,50 +109,60 @@ public class GuiceModuleAnnotationTests {
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@GuiceModule(excludeFilters=@Filter(type=FilterType.REGEX, pattern=".*"))
|
||||
@GuiceModule(excludeFilters = @Filter(type = FilterType.REGEX, pattern = ".*"))
|
||||
protected static class MetadataExcludesConfig {
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@GuiceModule(excludeNames="*")
|
||||
@GuiceModule(excludeNames = "*")
|
||||
protected static class MetadataExcludeNamesConfig {
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@GuiceModule(excludePatterns=".*")
|
||||
@GuiceModule(excludePatterns = ".*")
|
||||
protected static class MetadataExcludePatternsConfig {
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@GuiceModule(includeFilters=@Filter(type=FilterType.ASSIGNABLE_TYPE, value=Service.class))
|
||||
@GuiceModule(includeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, value = Service.class))
|
||||
protected static class MetadataIncludesConfig {
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Configuration
|
||||
@GuiceModule(includeNames="*service") // Bean name filter
|
||||
@GuiceModule(includeNames = "*service") // Bean name filter
|
||||
protected static class MetadataIncludeNamesConfig {
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Configuration
|
||||
@GuiceModule(includePatterns=".*service") // Bean name filter
|
||||
@GuiceModule(includePatterns = ".*service") // Bean name filter
|
||||
protected static class MetadataIncludePatternsConfig {
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Configuration
|
||||
@GuiceModule(includeFilters=@Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class))
|
||||
@GuiceModule(includeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, value = Foo.class))
|
||||
protected static class MetadataMoreIncludesConfig {
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Configuration
|
||||
public static class TestConfig {
|
||||
|
||||
@Bean
|
||||
public Service service() {
|
||||
return new MyService();
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public Map<String,String> someParameterizedType() {
|
||||
return new HashMap<String,String>();
|
||||
public Map<String, String> someParameterizedType() {
|
||||
return new HashMap<String, String>();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -56,7 +56,8 @@ public class ModuleBeanWiringTests extends AbstractCompleteWiringTests {
|
||||
@Configuration
|
||||
public static class TestConfig extends AbstractModule {
|
||||
|
||||
@Autowired Service service;
|
||||
@Autowired
|
||||
Service service;
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
@@ -80,16 +81,20 @@ public class ModuleBeanWiringTests extends AbstractCompleteWiringTests {
|
||||
public Baz baz(Service service) {
|
||||
return new Baz(service);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Parameterized<String> parameterizedBean() {
|
||||
return new Parameterized<String>() {};
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Parameterized<String> parameterizedBean() {
|
||||
return new Parameterized<String>() {
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected static class Spam {
|
||||
|
||||
public Spam(Service service) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -56,7 +56,8 @@ public class ModuleNamedBeanWiringTests extends AbstractCompleteWiringTests {
|
||||
@Configuration
|
||||
public static class TestConfig extends AbstractModule {
|
||||
|
||||
@Autowired Service service;
|
||||
@Autowired
|
||||
Service service;
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
@@ -86,16 +87,20 @@ public class ModuleNamedBeanWiringTests extends AbstractCompleteWiringTests {
|
||||
public Baz baz(Service service) {
|
||||
return new Baz(service);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Parameterized<String> parameterizedBean() {
|
||||
return new Parameterized<String>() {};
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Parameterized<String> parameterizedBean() {
|
||||
return new Parameterized<String>() {
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected static class Spam {
|
||||
|
||||
public Spam(Service service) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -31,17 +31,17 @@ import com.google.inject.Key;
|
||||
import com.google.inject.name.Names;
|
||||
|
||||
public class SpringInjectorTests {
|
||||
|
||||
|
||||
@Rule
|
||||
public ExpectedException expected = ExpectedException.none();
|
||||
|
||||
private SpringInjector injector = new SpringInjector(create());
|
||||
|
||||
private AnnotationConfigApplicationContext context;
|
||||
|
||||
|
||||
@After
|
||||
public void close() {
|
||||
if (context!=null) {
|
||||
if (context != null) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
@@ -87,16 +87,22 @@ public class SpringInjectorTests {
|
||||
|
||||
@Configuration
|
||||
public static class Additional {
|
||||
|
||||
@Bean
|
||||
public Service another() {
|
||||
return new MyService();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
public static class TestConfig {
|
||||
|
||||
@Bean
|
||||
public Service service() {
|
||||
return new MyService();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -36,22 +36,28 @@ public class SpringWiringTests extends AbstractCompleteWiringTests {
|
||||
|
||||
@Configuration
|
||||
public static class TestConfig {
|
||||
|
||||
@Bean
|
||||
public Service service() {
|
||||
return new MyService();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Thang thing() {
|
||||
return new Thang();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Thang other() {
|
||||
return new Thang();
|
||||
}
|
||||
@Bean
|
||||
public Parameterized<String> parameterizedBean() {
|
||||
return new Parameterized<String>() {};
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Parameterized<String> parameterizedBean() {
|
||||
return new Parameterized<String>() {
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -18,67 +18,75 @@ import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class DevelepmentStageInjectorTest {
|
||||
|
||||
@BeforeClass
|
||||
public static void init() {
|
||||
System.setProperty("spring.guice.stage", "DEVELOPMENT");
|
||||
}
|
||||
@BeforeClass
|
||||
public static void init() {
|
||||
System.setProperty("spring.guice.stage", "DEVELOPMENT");
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void cleanup() {
|
||||
System.clearProperty("spring.guice.stage");
|
||||
}
|
||||
@AfterClass
|
||||
public static void cleanup() {
|
||||
System.clearProperty("spring.guice.stage");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLazyInitBean() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DevelepmentStageInjectorTest.ModulesConfig.class);
|
||||
TestGuiceModule testGuiceModule = context.getBean(TestGuiceModule.class);
|
||||
assertFalse(testGuiceModule.getProviderExecuted());
|
||||
GuiceToken guiceToken = context.getBean(GuiceToken.class);
|
||||
assertTrue(testGuiceModule.getProviderExecuted());
|
||||
context.close();
|
||||
}
|
||||
@Test
|
||||
public void testLazyInitBean() {
|
||||
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
|
||||
DevelepmentStageInjectorTest.ModulesConfig.class);
|
||||
TestGuiceModule testGuiceModule = context.getBean(TestGuiceModule.class);
|
||||
assertFalse(testGuiceModule.getProviderExecuted());
|
||||
GuiceToken guiceToken = context.getBean(GuiceToken.class);
|
||||
assertTrue(testGuiceModule.getProviderExecuted());
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
static class ModulesConfig {
|
||||
@Bean
|
||||
public TestGuiceModule testGuiceModule() {
|
||||
return new TestGuiceModule();
|
||||
}
|
||||
@Configuration
|
||||
@EnableGuiceModules
|
||||
static class ModulesConfig {
|
||||
|
||||
@Bean
|
||||
public InjectorFactory injectorFactory() {
|
||||
return new TestDevelopmentStageInjectorFactory();
|
||||
}
|
||||
@Bean
|
||||
public TestGuiceModule testGuiceModule() {
|
||||
return new TestGuiceModule();
|
||||
}
|
||||
|
||||
}
|
||||
@Bean
|
||||
public InjectorFactory injectorFactory() {
|
||||
return new TestDevelopmentStageInjectorFactory();
|
||||
}
|
||||
|
||||
static class TestGuiceModule extends AbstractModule {
|
||||
private boolean providerExecuted = false;
|
||||
}
|
||||
|
||||
public boolean getProviderExecuted() {
|
||||
return this.providerExecuted;
|
||||
}
|
||||
static class TestGuiceModule extends AbstractModule {
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
}
|
||||
private boolean providerExecuted = false;
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
public GuiceToken guiceToken() {
|
||||
this.providerExecuted = true;
|
||||
return new GuiceToken();
|
||||
}
|
||||
}
|
||||
public boolean getProviderExecuted() {
|
||||
return this.providerExecuted;
|
||||
}
|
||||
|
||||
static class TestDevelopmentStageInjectorFactory implements InjectorFactory {
|
||||
@Override
|
||||
protected void configure() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Injector createInjector(List<Module> modules) {
|
||||
return Guice.createInjector(Stage.DEVELOPMENT, modules);
|
||||
}
|
||||
}
|
||||
@Provides
|
||||
@Singleton
|
||||
public GuiceToken guiceToken() {
|
||||
this.providerExecuted = true;
|
||||
return new GuiceToken();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class TestDevelopmentStageInjectorFactory implements InjectorFactory {
|
||||
|
||||
@Override
|
||||
public Injector createInjector(List<Module> modules) {
|
||||
return Guice.createInjector(Stage.DEVELOPMENT, modules);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class GuiceToken {
|
||||
|
||||
}
|
||||
|
||||
static class GuiceToken {}
|
||||
}
|
||||
|
||||
@@ -37,8 +37,7 @@ public class SpringModuleGuiceBindingAwareTests {
|
||||
@Test
|
||||
public void testAllDependenciesInjectedAndLifeycleMethodsCalledOnce() {
|
||||
Injector injector = Guice.createInjector(new SimpleGuiceModule(),
|
||||
new SpringModule(BeanFactoryProvider
|
||||
.from(GuiceProjectWithSpringLibraryTestSpringConfig.class)));
|
||||
new SpringModule(BeanFactoryProvider.from(GuiceProjectWithSpringLibraryTestSpringConfig.class)));
|
||||
|
||||
// check guice provided bindings
|
||||
assertNotNull(injector.getInstance(GuiceDependency1.class));
|
||||
@@ -55,12 +54,9 @@ public class SpringModuleGuiceBindingAwareTests {
|
||||
assertEquals("done", springBean.getDep1().doWork());
|
||||
|
||||
// check binding equality
|
||||
assertSame(injector.getInstance(IGuiceDependency1.class),
|
||||
AopTestUtils.getTargetObject(springBean.getDep1()));
|
||||
assertSame(injector.getInstance(IGuiceDependency2.class),
|
||||
AopTestUtils.getTargetObject(springBean.getDep2()));
|
||||
assertSame(injector.getInstance(IGuiceDependency3.class),
|
||||
AopTestUtils.getTargetObject(springBean.getDep3()));
|
||||
assertSame(injector.getInstance(IGuiceDependency1.class), AopTestUtils.getTargetObject(springBean.getDep1()));
|
||||
assertSame(injector.getInstance(IGuiceDependency2.class), AopTestUtils.getTargetObject(springBean.getDep2()));
|
||||
assertSame(injector.getInstance(IGuiceDependency3.class), AopTestUtils.getTargetObject(springBean.getDep3()));
|
||||
}
|
||||
|
||||
static class SimpleGuiceModule extends AbstractModule {
|
||||
@@ -73,10 +69,10 @@ public class SpringModuleGuiceBindingAwareTests {
|
||||
bind(IGuiceDependency2.class).toInstance(new IGuiceDependency2() {
|
||||
});
|
||||
// test provider binding
|
||||
bind(IGuiceDependency3.class)
|
||||
.toProvider(Providers.of(new IGuiceDependency3() {
|
||||
}));
|
||||
bind(IGuiceDependency3.class).toProvider(Providers.of(new IGuiceDependency3() {
|
||||
}));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -88,8 +84,7 @@ public class SpringModuleGuiceBindingAwareTests {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ApplicationListener<ApplicationEvent> eventListener(
|
||||
final IGuiceDependency1 dependency) {
|
||||
public ApplicationListener<ApplicationEvent> eventListener(final IGuiceDependency1 dependency) {
|
||||
return new ApplicationListener<ApplicationEvent>() {
|
||||
@Override
|
||||
public void onApplicationEvent(ApplicationEvent event) {
|
||||
@@ -97,38 +92,49 @@ public class SpringModuleGuiceBindingAwareTests {
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static interface IGuiceDependency1 {
|
||||
|
||||
String doWork();
|
||||
|
||||
}
|
||||
|
||||
static interface IGuiceDependency2 {
|
||||
|
||||
}
|
||||
|
||||
static interface IGuiceDependency3 {
|
||||
|
||||
}
|
||||
|
||||
static class GuiceDependency1 implements IGuiceDependency1 {
|
||||
|
||||
@Override
|
||||
public String doWork() {
|
||||
return "done";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static interface ISpringBean {
|
||||
|
||||
IGuiceDependency1 getDep1();
|
||||
|
||||
IGuiceDependency2 getDep2();
|
||||
|
||||
IGuiceDependency3 getDep3();
|
||||
|
||||
}
|
||||
|
||||
static class SpringBean implements ISpringBean {
|
||||
|
||||
private final IGuiceDependency1 dep1;
|
||||
|
||||
@Inject
|
||||
private IGuiceDependency2 dep2;
|
||||
|
||||
@Inject
|
||||
private IGuiceDependency3 dep3;
|
||||
|
||||
@@ -151,6 +157,7 @@ public class SpringModuleGuiceBindingAwareTests {
|
||||
public IGuiceDependency3 getDep3() {
|
||||
return dep3;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -95,9 +95,11 @@ public class SpringModuleMetadataTests {
|
||||
}
|
||||
|
||||
interface Service {
|
||||
|
||||
}
|
||||
|
||||
protected static class MyService implements Service {
|
||||
|
||||
}
|
||||
|
||||
public static class Foo {
|
||||
@@ -110,51 +112,62 @@ public class SpringModuleMetadataTests {
|
||||
|
||||
@Configuration
|
||||
protected static class MetadataExcludesConfig {
|
||||
|
||||
@Bean
|
||||
public GuiceModuleMetadata guiceModuleMetadata() {
|
||||
GuiceModuleMetadata metadata = new GuiceModuleMetadata();
|
||||
metadata.exclude(new AssignableTypeFilter(Service.class));
|
||||
return metadata;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
protected static class MetadataIncludesConfig {
|
||||
|
||||
@Bean
|
||||
public GuiceModuleMetadata guiceModuleMetadata() {
|
||||
GuiceModuleMetadata metadata = new GuiceModuleMetadata();
|
||||
metadata.include(new AnnotationTypeFilter(Cacheable.class));
|
||||
return metadata;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
public static class TestConfig {
|
||||
|
||||
@Bean
|
||||
public Service service() {
|
||||
return new MyService();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
public static class PrimaryConfig {
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public Service primary() {
|
||||
return new MyService();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
public static class MoreConfig {
|
||||
|
||||
@Bean
|
||||
public Service more() {
|
||||
return new MyService();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
public static class OtherConfig {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -35,12 +35,12 @@ public class SpringModuleWiringTests extends AbstractCompleteWiringTests {
|
||||
|
||||
@Override
|
||||
protected Injector createInjector() {
|
||||
return Guice.createInjector(new SpringModule(
|
||||
new AnnotationConfigApplicationContext(TestConfig.class)));
|
||||
return Guice.createInjector(new SpringModule(new AnnotationConfigApplicationContext(TestConfig.class)));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
public static class TestConfig {
|
||||
|
||||
@Bean
|
||||
public Service service() {
|
||||
return new MyService();
|
||||
@@ -66,5 +66,7 @@ public class SpringModuleWiringTests extends AbstractCompleteWiringTests {
|
||||
return new Parameterized<String>() {
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -31,13 +31,14 @@ public class SpringModuleWrappedTests {
|
||||
|
||||
@Test
|
||||
public void testDependenciesFromWrappedModule() {
|
||||
Injector injector = Guice.createInjector(new SpringModule(
|
||||
BeanFactoryProvider.from(TestConfig.class, ModuleProviderConfig.class)));
|
||||
Injector injector = Guice.createInjector(
|
||||
new SpringModule(BeanFactoryProvider.from(TestConfig.class, ModuleProviderConfig.class)));
|
||||
assertNotNull(injector.getInstance(Baz.class));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
public static class TestConfig {
|
||||
|
||||
@Bean
|
||||
public Baz baz(Service service) {
|
||||
return new Baz(service);
|
||||
@@ -46,9 +47,11 @@ public class SpringModuleWrappedTests {
|
||||
}
|
||||
|
||||
interface Service {
|
||||
|
||||
}
|
||||
|
||||
protected static class MyService implements Service {
|
||||
|
||||
}
|
||||
|
||||
public static class Foo {
|
||||
@@ -57,6 +60,7 @@ public class SpringModuleWrappedTests {
|
||||
public Foo(@Named("service") Service service) {
|
||||
service.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class Baz {
|
||||
|
||||
Reference in New Issue
Block a user