CDI beans injection

旧城冷巷雨未停 提交于 2020-01-21 19:16:07

问题


Is this a correct approach to inject @ApplicationScoped bean in @SessionScoped bean? will this lead my application scoped bean to be stored in the session of every user?

I have an application scoped bean that contains some values we share among all the system users, and now I need to get that values within a method in a session bean.


回答1:


Injecting a bean of the same or a broader scope in another bean is completely legal and correct either in JSF or CDI beans, like the example you provided.

The difference between CDI beans and JSF managed beans regarding that is when you try to inject a bean of a narrower scope in another bean (e.g inject @RequestScoped bean into @SessionScoped one), which is only possible as long as you are using CDI @Named beans, while not possible when working with JSF @ManagedBean.

The reason why this is possible for CDI beans is related to their Proxy Pattern mechanism, which is more flexible compared with the JSF mechanism (based on invoking the setters in order to directly inject a physical instance).

This proxy mechanism, allow the CDI container to pass a reference to a proxy instead of the injected bean (unless a bean has the default scope @Dependent). Therfore, that proxy will be responsbale of handling all calls to the injected bean and forward / redirect them to the correct bean instance.

See also:

  • CDI: Contexts and Dependency Injection for the Java EE platform - Client proxies
  • Java EE 6 @javax.annotation.ManagedBean vs. @javax.inject.Named vs. @javax.faces.ManagedBean
  • Backing beans (@ManagedBean) or CDI Beans (@Named)?
  • ManagedProperty in CDI @Named bean returns null


来源:https://stackoverflow.com/questions/28792974/cdi-beans-injection

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