Issue 30 in guiceyfruit: Injectors.close() in child injector

4 views
Skip to first unread message

codesite...@google.com

unread,
Oct 24, 2009, 6:09:41 PM10/24/09
to guiceyf...@googlegroups.com
Status: New
Owner: ----
Labels: Type-Defect Priority-Medium

New issue 30 by mathieu.carbou: Injectors.close() in child injector
http://code.google.com/p/guiceyfruit/issues/detail?id=30

Hi,

I create an injector with the Jsr250Module. Them from it i create a child
injector where i have a binding using @PostConstruct and @PreDestroy.

When i request my instance, the method annotated with @PostConstruct is
called correctly even in child injectors.

But when i "close" the child injector using Injectors.close(child), the
method annotated by @PreDestroy in the binding of the child injector is not
called. This is because the PreDestroyCloser is bound in the parent
injector.

Here is a use case:

final class PreDestroyInChildInjector {
public static void main(String... args) throws CloseFailedException {
Injector parent = Guice.createInjector(new Jsr250Module());
Injector child = parent.createChildInjector(new AbstractModule() {
@Override
protected void configure() {
bind(MyClass.class).in(Singleton.class);
}
});
child.getInstance(MyClass.class);
Injectors.close(child);
}

public static class MyClass {
@PostConstruct
public void start() { System.out.println("start called"); }
@PreDestroy
public void stop() { System.out.println("stop called"); }
}
}

A fix I've found would be in the Injectors class, instead of calling
injector.getBindings(), call a method instead:
Injectors.getAllBindings(Injector i) which will return the complete set of
available bindings from the child to the top parent, and not only those
from the current child injector:

public Map<Key<?>, Binding<?>> getAllBindings(Injector i) {
Map<Key<?>, Binding<?>> all = new LinkedHashMap<Key<?>, Binding<?>>();
while (i != null) {
all.putAll(i.getBindings());
i = i.getParent();
}
return all;
}

NB: i first tried to call Injectors.close(child) and then
Injectors.close(child.getParent) but obviously it does not work since the
first call does not find the Closer binding and the second call does not
find the MyClass binding in its child.

--
You received this message because you are listed in the owner
or CC fields of this issue, or because you starred this issue.
You may adjust your issue notification preferences at:
http://code.google.com/hosting/settings

Reply all
Reply to author
Forward
0 new messages