简体   繁体   中英

CDI beans injection

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.

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 (eg 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM