1

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.

Tarik
  • 4,546
  • 3
  • 33
  • 64
Jim
  • 117
  • 1
  • 12
  • Your question is quite vague. Can you illustrate exactly what you want to do? Besides, its quite safe to inject application-scoped beans into session beans, and vice-versa. – maress Mar 01 '15 at 11:38
  • Hello Maress, you already answered my question that its quite safe to inject application scopped int session beans. I will appriciate if you answer this question and will mark this answered but I will be very grateful if you give more explanation why its safe. – Jim Mar 01 '15 at 12:24

1 Answers1

5

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:

Community
  • 1
  • 1
Tarik
  • 4,546
  • 3
  • 33
  • 64
  • 2
    It's just possible in JSF, too. Only the other way round (injecting a session scoped bean in an application scoped bean) is not possible in JSF managed beans. It's indeed for precisely the proxy pattern reason only possible in CDI. – BalusC Mar 02 '15 at 07:01
  • @BalusC what happened is that i was thinking the opposite while answering (that he is injecting a narrower scoped bean). Thanks for your guidance – Tarik Mar 02 '15 at 10:40
  • Hi, If, for example, i inject a *VS bean(ViewScoped)* in a *ApplicationScoped bean* and there is more than one *VS bean*, **1-** Which one will be injected? **2-** Is there a situation where there is no *VS bean* to inject? if so, What will happen? – Arash Aug 17 '20 at 15:40