のようなセッションスコープのプロバイダーを作成する必要がありますServletScopes.SESSION
が、オブジェクトの構築後に1つの追加アクション(リスナーの追加など)があります。最初のアイデア-いくつかのメソッドを拡張ServletScopes.SESSION
してオーバーライドしますが、残念ながらServletScopes.SESSION
オブジェクトであり、クラスではありません。では、ServletScopesからコードをコピーして貼り付けることなく、このようなプロバイダーを取得するにはどうすればよいですか?
1 に答える
1
最初に注釈を作成します。
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @interface AfterInjectionListener
{
}
次に、メソッド `afterInjection()' を実装するすべてのクラスに注釈を付け、このバインディングを Guice モジュールの 1 つに追加します。
bindListener(Matchers.any(), new TypeListener()
{
@Override
public <I> void hear(TypeLiteral<I> typeLiteral, TypeEncounter<I> iTypeEncounter)
{
if (typeLiteral.getRawType().isAnnotationPresent(AfterInjectionListener.class))
{
logger.debug("adding injection listener {}", typeLiteral);
iTypeEncounter.register(new InjectionListener<I>()
{
@Override
public void afterInjection(I i)
{
try
{
logger.debug("after injection {}", i);
i.getClass().getMethod("afterInjection").invoke(i);
} catch (NoSuchMethodException e)
{
logger.trace("no such method", e);
} catch (Exception e)
{
logger.debug("error after guice injection", e);
}
}
});
}
}
});
メソッド内にブレークポイントを配置しafterInjection()
、デバッグ モードでアプリを実行し、インジェクション後にメソッドが呼び出されるかどうかを確認します。
于 2011-02-24T14:26:28.183 に答える