---
title: CDI Instance Injections and Session/Application Scoped Beans
layout: blog
author: Cody Lerum
email: cody.lerum@gmail.com
tags: [ java, cdi ]
---
If you've spent much time with CDI you invariably had a use case where you would prefer not to trigger an injection
when the bean is initialized. This can be handy for example if it is an expensive action and the injected bean is only
going be be invoked a small percentage of the time.

There is however caveat that is relevant. The beans produced by the Instance  will live until the containing bean is destroyed.

This doesn't cause an issue with Dependent, Request, View, or Conversation scoped beans, but it would cause a unexpected
memory leak with Application or even Session scoped beans. Since the Instance could be invoked multiple times spanning
hours or days with a +@SessionScoped+ bean and potentially weeks or months with an +@ApplicationScoped+ bean (if your
lucky to run your app uninterrupted that long) the memory leak could bring your app to a halt.

Improvement are being made to the CDI 1.1 spec to handled this better https://issues.jboss.org/browse/CDI-139[CDI-139]

But in the meantime the following will work nicely

[source,java]
----
@Inject
BeanManager bm;

public void run() {

  CreationalContext<Foo> ctx = bm.createCreationalContext(null);
  Bean<?> beans = BeanManagerTools.beans(bm, Foo.class);
  Foo f = bm.getReference(beans, Foo.class, ctx);

  //Do Work

  ctx.release();
}
----

Calling the release at the end destroys all the beans created in the Context we initialized (ctx)



