When, exactly, @Inject annotation initiates injection of SessionScoped bean in Servlet?

前端 未结 2 1700
执笔经年
执笔经年 2020-12-20 18:35

I need to modify a user session object (SessionScoped bean - CDI) in a Servlet, so I have to obtain that bean somehow. I used injection in the following way:



        
相关标签:
2条回答
  • 2020-12-20 19:31

    The CDI uses the proxy pattern. The injected instance is actually not the real instance, but a proxy which locates the real instance depending on the current context and delegates all methods to it (like as how EJBs work). The autogenerated class of your UserSession bean looks roughly like this:

    public UserSessionCDIProxy extends UserSession implements Serializable {
    
        public String getSomeProperty() {
            UserSession instance = CDI.resolveItSomehow();
            return instance.getSomeProperty();
        }
    
        public void setSomeProperty(String someProperty) {
            UserSession instance = CDI.resolveItSomehow();
            instance.setSomeProperty(someProperty);
        }
    
    }
    

    This mechanism allows you to inject instances of a narrower scope in instances of a broader scope and allows you to still get the expected instance in the current context. The standard JSF @ManagedProperty annotation doesn't support it, simply because it does not use a proxy, but injects the desired instance directly. That's why it's not possible to inject something of a narrower scope by @ManagedProperty.

    See also:

    • Backing beans (@ManagedBean) or CDI Beans (@Named)?
    • Get JSF managed bean by name in any Servlet related class
    • When using @EJB, does each managed bean get its own @EJB instance?
    • How to choose the right bean scope?
    0 讨论(0)
  • 2020-12-20 19:40

    Your answer lies in the C of CDI, which stands for Contexts.

    What happens is that not the actual bean is injected, but a proxy. This proxy is contextual and resolves to the actual session scoped bean depending on the context of the caller on who's behalf the proxy is executed.

    0 讨论(0)
提交回复
热议问题