Question

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?

Was it helpful?

Solution 3

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.

OTHER TIPS

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.

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?

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