When exactly does the @ Introductory annotation trigger the injection of a SessionScoped bean into a Servlet?

I need to change the user session object (SessionScoped bean - CDI) in the servlet, so I have to somehow get this bean. I used the injection as follows:

@Inject private UserSession user; 

where UserSession is the SessionScoped CDI bean. custom methods are called from doPost or doGet methods. This works great; every time the @Inject annotation introduces the corresponding UserSession bean, but I don’t understand how this behavior is achieved.

I assumed that beans annotated with @Inject are only entered once (when the object is created - an instance of the servlet in this case), but this is obviously a false presumption.

So when are these beans introduced in the servlet? On request? And how does this approach avoid conflicts (one servlet instance β€” several threads to deal with it) when there are several UserSession objects?

+6
source share
2 answers

CDI uses a proxy template . The injection instance is actually not a real instance, but a proxy server that finds the real instance depending on the current context and delegates all methods to it (for example, how EJBs work). The autogenerated class of your UserSession bean looks something 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 into instances of a wider scope and allows you to get the expected instance in the current context. The JSF @ManagedProperty standard annotation @ManagedProperty not support it, simply because it does not use a proxy, but enters the desired instance directly. That's why it was not possible to introduce something narrower with @ManagedProperty .

See also:

+5
source

Your answer lies with C CDI, which denotes contexts.

It happens that the actual bean is not entered, but a proxy. This proxy server is contextual and resolves the actual area of ​​the bean session depending on the context of the caller on whose behalf the proxy server is running.

+4
source

Source: https://habr.com/ru/post/904609/


All Articles