2010-05-26 75 views

回答

3

現在看來,這是尚未支持,所以對於大家如何要這項工作,這裏是小解決方案。

public class PostConstructListener implements TypeListener{ 

    private static Logger logger = Logger.getLogger(PostConstructListener.class); 

    @Override 
    public <I> void hear(TypeLiteral<I> iTypeLiteral,final TypeEncounter<I> iTypeEncounter) { 

     Class<? super I> type = iTypeLiteral.getRawType(); 

     ReflectionUtils.MethodFilter mf = new ReflectionUtils.MethodFilter() { 
      @Override 
      public boolean matches(Method method) { 
       return method.isAnnotationPresent(PostConstruct.class); 
      } 
     }; 

     ReflectionUtils.MethodCallback mc = new ReflectionUtils.MethodCallback() { 
      @Override 
      public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { 
       if (!(method.getReturnType().equals(Void.TYPE) && method.getParameterTypes().length == 0)) 
       { 
        logger.warn("Only VOID methods having 0 parameters are supported by the PostConstruct annotation!" + 
          "method " + method.getName() + " skipped!"); 
        return; 

       } 
       iTypeEncounter.register(new PostConstructInvoker<I>(method)); 
      } 
     }; 

     ReflectionUtils.doWithMethods(type,mc,mf); 
    } 

    class PostConstructInvoker<I> implements InjectionListener<I>{ 

     private Method method; 

     public PostConstructInvoker(Method method) { 
      this.method = method; 
     } 

     @Override 
     public void afterInjection(I o) { 
      try { 
       method.invoke(o); 
      } catch (Throwable e) { 
       logger.error(e); 
      } 
     } 
    } 
} 

ReflectionUtils包是在spring中定義的。

綁定這個監聽器與任何事件:

bindListener(Matchers.any(),new PostConstructListener()); 
您吉斯模塊中

。玩得開心

5

我想使用@PostConstruct是要走的路。

這裏有一個相關的博客帖子:http://macstrac.blogspot.com/2008/10/adding-support-for-postconstruct.html

這裏是一個插件庫,它提供了支持:http://code.google.com/p/guiceyfruit/

通過Guiceyfruit添加生命週期支持,在此說明:http://code.google.com/p/guiceyfruit/wiki/Lifecycle

+0

'@ PostConstruct'是Spring中的首選方法,也是 – skaffman 2010-05-26 11:14:45

+0

我只是不明白,是否必須下載一些補丁來添加支持此JRS註釋? – Roman 2010-05-26 11:17:37

3

你想在維基吉斯閱讀CustomInjections頁:

除了標準@Inject驅動的注射,吉斯包括定製注射掛鉤。這使得Guice可以託管其他擁有自己的注入語義或註釋的框架。大多數開發人員不會直接使用自定義注入;但他們可能會看到他們在擴展和第三方庫中的使用。每個自定義注入都需要一個類型監聽器,一個注入監聽器以及每個註冊監聽器。

8

到目前爲止,最簡單的解決辦法,如果你使用構造器注入,而不是做任何事情太瘋狂了,是創建工後法與@Inject標註爲:

final class FooImpl implements Foo { 
    private final Bar bar; 

    @Inject 
    FooImpl(Bar bar) { 
    this.bar = bar; 

    ... 
    } 

    @Inject 
    void init() { 
    // Post-construction code goes here! 
    } 
} 

當吉斯提供FooImpl,它會看到它有一個@Inject的構造函數,調用它,然後搜索用@Inject註釋的方法並調用它們。用於此目的的用例是setter注入,但即使@Inject方法沒有參數,Guice也會調用它。

如果您使用setter或field injection來注入deps,我不建議使用它,因爲我不知道Guice是否會對@Inject方法的調用順序做出任何保證(即您的init()方法可能不能保證被稱爲最後)。也就是說,無論如何,構造函數注入是首選的方法,所以這應該是一個非問題。