Question

I would like to have my own contexts for some CDI-based projects. I need (want) custom scopes so that I can isolate the how long a component lives and where.

To implement your own context, you need to implement the Context interface which is pretty self-explanatory, but how or where to you really define when it is created?

Was it helpful?

Solution

I haven't tested this yet, but I believe this will work. For each custom scope/context you want in your application, you simply need to add that context via an extension when the container is initialized:

public void afterBeanDiscovery(@Observes AfterBeanDiscover afterBeanDiscovery, BeanManager beanManager)
{
  CustomContext customContext = new CustomContext();
  afterBeanDiscovery.addContext(customContext);

  beanManager ...
}

Now, the trick is, you need to hold a reference to that context so then when you want to start or stop it, you can. That would be something like:

@Inject
protected HttpRequestLifecycle httpRequestLifecycle;

public void doSomething()
{
  startContext();
  doStuff();
  stopContext();
}

public void startContext()
{
  httpRequestContextLifecycle.getHttpRequestContext().activate();
}

That should do it, there isn't a wealth of documentation out there, so I hope this helps.

Anyone interested, check out the source here: http://github.com/walterjwhite/server.web.application

Walter

OTHER TIPS

Check this DZone article: Custom scopes in CDI 1.0 and Spring 3.1 (bottom half)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top