Inject Bean into CDI Context programmatically?

感情迁移 提交于 2019-12-21 13:05:10

问题


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?


回答1:


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.




回答2:


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.




回答3:


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?



来源:https://stackoverflow.com/questions/21538679/inject-bean-into-cdi-context-programmatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!