Shadowman
Shadowman

Reputation: 12039

Inject Bean into CDI Context programmatically?

Is it possible to manually Inject a bean into a CDI context? With the JBoss Seam framework, I could always do something like Contexts.getConversationContext().set("foo", bar); and the Bean would become part of that context. Is it possible to do something like this in Java EE 6 CDI?

Upvotes: 7

Views: 5007

Answers (3)

Adrian Mitev
Adrian Mitev

Reputation: 4752

With CDI you have to slightly change the way you think about the scoped beans. In Seam2 the contexts are just maps that are held in a specific scope and you have access to these maps. In CDI the container gets the control over the contexts and allows you only to declare beans in a concrete scope and everything gets managed behind the scene without access to the scope maps. This is done because CDI philosophy is to keep the things type-safe and just setting things in a map with a string as a value and injecting them by their string key isn't type-safe at all.

To achieve the goal you want create a "holder" bean in the concrete scope and hold your values there.

@Named
@ConversationScoped
public class UserManager {

  private User currentUser;

  //getters and setters for currentUser

}

In this sample the a User instance is held in the conversation scope by setting it in the conversation-scoped bean. This is completely type-safe as you can inject the UserManager anywhere you want just by using @Inject (actually it's bean type gets used) avoiding string keys (as in Seam2) that are unsafe when doing refactoring.

Upvotes: 4

LightGuard
LightGuard

Reputation: 5378

There is no way to do this in an implementation agnostic way. You'd have to dig into the implementation, find the scope objects, pull them out via a BeanManager and figure out how to add them. Not all of them (quite possibly none of them) are as easy to set as maps.

Upvotes: -1

EdH
EdH

Reputation: 5003

Isn't that possible using Producer methods?

http://docs.jboss.org/weld/reference/1.0.0/en-US/html/producermethods.html

I've done this to create the objects that get injected into my beans.

While I haven't used this, there is also the BeanManager interface

http://docs.jboss.org/weld/reference/1.0.0/en-US/html/extend.html

Or are you after something specific in the Conversation scope?

Upvotes: 3

Related Questions