CDI - Writing Custom Contexts and Areas

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

To implement your own context, you need to implement the Context interface, which is pretty straightforward, but how and where do you really determine when it is created?

+7
scope cdi
source share
2 answers

I have not tested this yet, but I believe that it will work. For each custom area / context that you want in your application, you just need to add this context through the extension when initializing the container:

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

Now, the trick, you need to link to this context, so that later, when you want to start or stop it, you can. It will be something like:

 @Inject protected HttpRequestLifecycle httpRequestLifecycle; public void doSomething() { startContext(); doStuff(); stopContext(); } public void startContext() { httpRequestContextLifecycle.getHttpRequestContext().activate(); } 

This should do it, there is not a lot of documentation there, so I hope this helps.

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

Walter

+4
source share

Check out this Dzone article: User Areas in CDI 1.0 and Spring 3.1 (bottom half)

+1
source share

All Articles