Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 396
Shadowman Avatar asked Feb 03 '14 21:02

Shadowman


2 Answers

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.

like image 145
Adrian Mitev Avatar answered Nov 15 '22 03:11

Adrian Mitev


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?

like image 23
EdH Avatar answered Nov 15 '22 02:11

EdH