Méthode d’initialisation d’appel de guice après avoir instantané un object

Est-il possible de demander à Guice d’appeler une méthode (c.-à-d. Init ()) après avoir créé un object de type donné?

Je recherche une fonctionnalité similaire à l’annotation @PostConstruct dans EJB 3.

En fait, c’est possible.

Vous devez définir un TypeListener pour obtenir les fonctionnalités. Quelque chose dans le sens de ce qui suit dans votre définition de module:

 bindListener(Matchers.subclassesOf(MyInitClass.class), new TypeListener() { @Override public  void hear(final TypeLiteral typeLiteral, TypeEncounter typeEncounter) { typeEncounter.register(new InjectionListener() { @Override public void afterInjection(Object i) { MyInitClass m = (MyInitClass) i; m.init(); } }); } }); 

Vous pouvez simplement append l’annotation @Inject à votre méthode init() . Il sera exécuté automatiquement une fois l’object instancié.

J’aime http://code.google.com/p/mycila/wiki/MycilaGuice . Cela prend en charge Guice 3, autre que http://code.google.com/p/guiceyfruit .

guiceyfruit fait ce que vous recherchez pour les méthodes annotées avec @PostConstruct ou implémentant InitializingBean de Spring. Il est également possible d’écrire vos propres auditeurs pour le faire. Voici un exemple qui appelle une méthode publique init() après la création d’objects.

 import com.google.inject.*; import com.google.inject.matcher.*; import com.google.inject.spi.*; public class MyModule extends AbstractModule { static class HasInitMethod extends AbstractMatcher> { public boolean matches(TypeLiteral tpe) { try { return tpe.getRawType().getMethod("init") != null; } catch (Exception e) { return false; } } public static final HasInitMethod INSTANCE = new HasInitMethod(); } static class InitInvoker implements InjectionListener { public void afterInjection(Object injectee) { try { injectee.getClass().getMethod("init").invoke(injectee); } catch (Exception e) { /* do something to handle errors here */ } } public static final InitInvoker INSTANCE = new InitInvoker(); } public void configure() { bindListener(HasInitMethod.INSTANCE, new TypeListener() { public  void hear(TypeLiteral type, TypeEncounter encounter) { encounter.register(InitInvoker.INSTANCE); } }); } } 

GWizard comprend un module ( gwizard-services ) qui fournit des services Guava dans un format compatible avec Guice. Les services de goyave vous permettent de gérer le cycle de vie dans des threads parallèles.

https://github.com/stickfigure/gwizard