是否可以告诉Guice在之后调用某个方法(即init()) 即时提供给定类型的对象?
我在EJB 3中寻找类似于@PostConstruct注释的功能。
答案 0 :(得分:55)
您只需将@Inject
注释添加到init()
方法即可。它将在实例化对象后自动运行。
答案 1 :(得分:34)
实际上,这是可能的。
您需要定义TypeListener
才能使功能正常运行。模块定义中的以下内容:
bindListener(Matchers.subclassesOf(MyInitClass.class), new TypeListener() {
@Override
public <I> void hear(final TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) {
typeEncounter.register(new InjectionListener<I>() {
@Override
public void afterInjection(Object i) {
MyInitClass m = (MyInitClass) i;
m.init();
}
});
}
});
答案 2 :(得分:7)
guiceyfruit执行使用@PostConstruct
注释或实现spring InitializingBean
的方法。也可以编写自己的侦听器来执行此操作。这是一个在创建对象后调用公共init()
方法的示例。
import com.google.inject.*;
import com.google.inject.matcher.*;
import com.google.inject.spi.*;
public class MyModule extends AbstractModule {
static class HasInitMethod extends AbstractMatcher<TypeLiteral<?>> {
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 <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
encounter.register(InitInvoker.INSTANCE);
}
});
}
}
答案 3 :(得分:7)
我喜欢http://code.google.com/p/mycila/wiki/MycilaGuice。这支持Guice 3,而不是http://code.google.com/p/guiceyfruit。
答案 4 :(得分:1)
GWizard包含一个模块(gwizard-services
),它以Guice友好格式提供Guava服务。 Guava服务为您提供并行线程的生命周期管理。
答案 5 :(得分:0)
如果您需要使用其他对象初始化一个对象,并且在两个对象都准备好之后(如果您需要彼此注册,并且它们也彼此依赖,则是这种情况),您可以轻松地做到这一点: / p>
public final class ApplicationModule extends AbstractModule {
@Override
protected void configure() {
requestStaticInjection(ApplicationModule.class);
}
@Inject
static void injectApplication(
ReslSession reslSession,
Set<Saga> sagas,
Set<Reaction> reactions
) {
sagas.forEach(reslSession::registerSaga);
reactions.forEach(reslSession::registerReaction);
}
}
答案 6 :(得分:0)
如果您想在实例创建后调用方法,则意味着构造后方法调用实际上是实例创建的步骤。在这种情况下,我建议使用抽象工厂设计模式来解决此问题。 代码可能看起来像这样:
class A {
public A(Dependency1 d1, Dependency2 d2) {...}
public postConstruct(RuntimeDependency dr) {...}
}
interface AFactory {
A getInstance(RuntimeDependency dr);
}
class AFactoryImpl implements AFactory {
@Inject
public AFactoryImpl(Dependency1 d1, Dependency2 d2) {...}
A getInstance(RuntimeDependency dr) {
A a = new A(d1, d2);
a. postConstruct(dr);
return a;
}
}
// in guice module
bind(AFactory.class).to(AFactoryImpl.class)
答案 7 :(得分:-1)
基于Geoff's answer,您可以“使之可调用” @PostConstruct
方法:
public class GuiceExample {
@Inject
private IDataManager dataManager;
public GuiceExample() {
System.out.println("Constructor");
}
@PostConstruct
private void init() {
dataManager.printData();
}
public static void main(String[] args) {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(IDataManager.class).to(DataManager.class);
bindListener(HasPostConstructAnnotationMatcher.INSTANCE, new TypeListener() {
@Override
public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) {
encounter.register(PostConstructAnnotationInvoker.INSTANCE);
}
});
}
});
GuiceExample example = injector.getInstance(GuiceExample.class);
}
private static class HasPostConstructAnnotationMatcher extends AbstractMatcher<TypeLiteral<?>> {
private static final HasPostConstructAnnotationMatcher INSTANCE = new HasPostConstructAnnotationMatcher();
@Override
public boolean matches(TypeLiteral<?> t) {
return Arrays.stream(t.getRawType().getDeclaredMethods()).anyMatch(GuiceExample::hasPostConstructAnnotation);
}
}
private static boolean hasPostConstructAnnotation(Method method) {
Annotation[] declaredAnnotations = method.getAnnotations();
return Arrays.stream(declaredAnnotations).anyMatch(a -> a.annotationType().equals(PostConstruct.class));
}
private static class PostConstructAnnotationInvoker implements InjectionListener<Object> {
private static final PostConstructAnnotationInvoker INSTANCE = new PostConstructAnnotationInvoker();
@Override
public void afterInjection(Object injectee) {
//@formatter:off
Arrays.stream(injectee.getClass().getDeclaredMethods())
.filter(GuiceExample::hasPostConstructAnnotation)
.forEach(m -> {
try {
m.setAccessible(true);
m.invoke(injectee);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
});
//@formatter:on
}
}
public static interface IDataManager {
void printData();
}
public static class DataManager implements IDataManager {
@Override
public void printData() {
System.out.println("I print data.");
}
}
}
此外,您可以有多个@PostConstruct
方法,但是您将不知道它们将以什么顺序被调用:
@PostConstruct
private void init() {
dataManager.printData();
}
@PostConstruct
private void init2() {
System.out.println("Other init method");
}