Java Guice,AfterPropertieSet
有人知道如何在Guice中实现与spring中的“”接口相同的功能?Java Guice,AfterPropertieSet,java,guice,Java,Guice,有人知道如何在Guice中实现与spring中的“”接口相同的功能? (这是一个后期构建挂钩)我想使用@PostConstruct是一个不错的选择 以下是一篇相关的博文: 下面是一个提供支持的插件库: 这里介绍了通过Guiceyfruit添加生命周期支持:它似乎还不受支持,所以对于每个人来说,这是一个小的解决方案 public class PostConstructListener implements TypeListener{ private static Logger logge
(这是一个后期构建挂钩)我想使用@PostConstruct是一个不错的选择 以下是一篇相关的博文: 下面是一个提供支持的插件库:
这里介绍了通过Guiceyfruit添加生命周期支持:它似乎还不受支持,所以对于每个人来说,这是一个小的解决方案
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);
}
}
}
}
在您的guice模块中。玩得开心您会想阅读Guice wiki上的页面:
除了标准的@Inject
驱动的注入之外,Guice还包括用于定制注入的挂钩。这使Guice能够承载具有自己的注入语义或注释的其他框架。大多数开发人员不会直接使用自定义注入;但它们可能会在扩展和第三方库中看到它们的用途。每个自定义注入都需要一个类型侦听器、一个注入侦听器以及每个类型的注册
到目前为止,最简单的解决方案是,如果您正在使用构造函数注入,并且没有做任何太疯狂的事情,那么创建一个后期构造方法,并使用
@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!
}
}
当Guice提供FooImpl时,它将看到它有一个@Inject
构造函数,调用它,然后搜索带有@Inject
注释的方法并调用它们。这种方法的预期用例是setter注入,但即使@Inject
方法没有参数,Guice也会调用它
如果您使用setter或field injection来注入deps,我不建议使用此选项,因为我不知道Guice是否保证调用
@injecte
方法的顺序(也就是说,您的init()
方法可能不能保证最后调用)。也就是说,构造函数注入是首选方法,所以这应该不是问题。@PostConstruct
是春季的首选方法,我也不明白,我需要下载一些补丁来添加对这个JRS注释的支持吗?你指的接口是InitializingBean
final class FooImpl implements Foo {
private final Bar bar;
@Inject
FooImpl(Bar bar) {
this.bar = bar;
...
}
@Inject
void init() {
// Post-construction code goes here!
}
}