Java 提供者扩展
我需要为会话作用域创建提供程序,比如Java 提供者扩展,java,guice,provider,guice-servlet,Java,Guice,Provider,Guice Servlet,我需要为会话作用域创建提供程序,比如ServletScopes.session,但是在对象构造之后需要一个额外的操作(比如addlistener)。第一个想法-扩展ServletScopes.SESSION并重写某些方法,但不幸的是ServletScopes.SESSION是对象,而不是类。那么,如何在不从ServletScopes复制粘贴代码的情况下获得这样的提供程序呢?首先创建一个注释: import java.lang.annotation.Retention; import java.l
ServletScopes.session
,但是在对象构造之后需要一个额外的操作(比如addlistener)。第一个想法-扩展ServletScopes.SESSION
并重写某些方法,但不幸的是ServletScopes.SESSION
是对象,而不是类。那么,如何在不从ServletScopes复制粘贴代码的情况下获得这样的提供程序呢?首先创建一个注释:
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()”方法的每个类进行注释,并将此绑定添加到一个GUI模块:
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);
}
}
});
}
}
});
bindListener(Matchers.any(),new-TypeListener())
{
@凌驾
public void hear(TypeLiteral-TypeLiteral,typeconference-ittypeconference)
{
if(typeLiteral.getRawType().isAnnotationPresent(AfterInjectionListener.class))
{
debug(“添加注入侦听器{}”,typeLiteral);
注册(新的InjectionListener())
{
@凌驾
公共无效后注(一)
{
尝试
{
debug(“注入后{}”,i);
i、 getClass().getMethod(“后注入”).invoke(i);
}捕获(无此方法例外)
{
logger.trace(“无此类方法”,e);
}捕获(例外e)
{
调试(“guice注入后出错”,e);
}
}
});
}
}
});
在
afterInjection()
方法中放置一个断点,在调试模式下运行应用程序,检查该方法是否在注入后调用。Ok。谢谢但是对于每个这样简单的操作,似乎都有很多代码)在Guice实现Java的标准注解@AfterInjection之前,我们必须使用这些代码。也许使用Guice 3.0。我们拭目以待