本文介绍了Guice,afterPropertiesSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人知道如何在Guice中实现与'界面?
(它是一个帖子构建钩子)
Someone knows some way that how can I achieve the same functionality in Guice as the 'afterPropertiesSet' interface in spring ? ( its a post construction hook )
推荐答案
它似乎还没有支持,所以对于每个人来说这是怎么想要的工作,这是一个小解决方案。
It seems it is not yet supported , so for everyone how wants this work , here is small solution.
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);
}
}
}
}
定义包在春天。
将此监听器绑定到任何事件:
Bind this listener to any event with :
bindListener(Matchers.any(),new PostConstructListener());
。玩得开心
这篇关于Guice,afterPropertiesSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!