我想对一些基于CDI的项目有自己的背景。我需要(想要)自定义范围,以便我可以隔离组件的存放时间和位置。
要实现自己的上下文,您需要实现Context接口,这个接口非常简单,但是在创建它时如何或在何处真正定义它?
答案 0 :(得分:4)
我还没有测试过,但我相信这会有效。对于您在应用程序中需要的每个自定义范围/上下文,只需在初始化容器时通过扩展添加该上下文:
public void afterBeanDiscovery(@Observes AfterBeanDiscover afterBeanDiscovery, BeanManager beanManager)
{
CustomContext customContext = new CustomContext();
afterBeanDiscovery.addContext(customContext);
beanManager ...
}
现在,诀窍是,您需要保持对该上下文的引用,以便当您想要启动或停止它时,您可以。那将是这样的:
@Inject
protected HttpRequestLifecycle httpRequestLifecycle;
public void doSomething()
{
startContext();
doStuff();
stopContext();
}
public void startContext()
{
httpRequestContextLifecycle.getHttpRequestContext().activate();
}
应该这样做,那里没有大量的文档,所以我希望这会有所帮助。
有兴趣的人,请查看来源: http://github.com/walterjwhite/server.web.application
沃尔特
答案 1 :(得分:1)
查看此DZone文章:Custom scopes in CDI 1.0 and Spring 3.1 (下半部分)