How to instantiate Spring bean using custom scope and @Autowired attributes?

In our project, we use Spring request scoped beans. Now we have a requirement to support asynchronous requests, and the scoped beans request does not work for child threads. I know RequestContextFilter , and it "supports" for async, but it seems that RequestContextFilter expects the main thread to wait for child threads that are not suitable for us. Our main thread returns immediately after new threads appear using the @Async annotation, and the DispatcherServlet clears the RequestContextHolder . That way, when the child threads get to the point where they need the bean request, @Autowired fails.

I also know SimpleThreadScope , but it does not clear the local attributes of the thread and in the situation of a thread pool, it is not only dangerous to use, but also useless.

I need a custom scope. So far I have found 3 useful examples, but all of them do not justify the fact that the beans that they create as part of the user area are simple POJOs without any dependencies. It goes without saying that this does not exist in real life. Can anyone suggest a way to instantiate beans that have @Autowired beans dependencies on other areas?

What I have found so far:

https://github.com/spring-by-example/spring-by-example/tree/master/modules/sbe-thread-scope/src/main/java/org/springbyexample/bean/scope/thread

https://github.com/billkoch/spring-async-mdc

Spring Bean Custom Scale JMS

+1
source share
1 answer

Continuing the discussion of another issue :

See Spring documentation on beans scope for dependencies .

.

I mean <aop:scoped-proxy/> , which the link points to. Each time an auto-reinforcement field is referenced, the user-defined get() method is called to find an instance based on some criteria.

.

I understand that I can look for dependencies (although I don’t know how the scope is not a bean, maybe I need to pass the application context during instance creation?). I do not understand how to insert these dependencies into my bean if they are @Autowired marked? Or are you saying that the bean user area should not have @Autowired dependencies?

It works automatically; Spring introduces a proxy for the bean, and scope.get() is called every time the method on that bean is called, returning the specific instance you want in the context of the current call.

Take a look at AbstractRequestAttributesScope to see how it works (in this case it gets an instance from an HTTP request and, if it does not exist, creates it).

So your code calls foo() on the proxy; the structure calls the region to get the desired instance, and then calls foo() on that instance.

The discovered methods that you want to call must either be on the interface or not declared final .

+1
source

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


All Articles