Guice and RequestScoped behaviour in multiple threads

后端 未结 3 1993
情深已故
情深已故 2021-01-06 08:04

I am using Guice\'s RequestScoped and Provider in order to get instances of some classes during a user request. This works fine currently. Now I want to do some job in a bac

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-06 08:57

    I have faced the exact same problem but solved it in a different way. I use jOOQ in my projects and I have implemented transactions using a request scope object and an HTTP filter.

    But then I created a background task which is spawned by the server in the middle of the night. And the injection is not working because there is no request scope.

    Well. The solutions is simple: create a request scope manually. Of course there is no HTTP request going on but that's not the point (mostly). It is the concept of the request scope. So I just need a request scope that exists alongside my background task.

    Guice has an easy way to create a request scope: ServletScope.scopeRequest.

    public class MyBackgroundTask extends Thread {
        @Override
        public void run() {
            RequestScoper scope = ServletScopes.scopeRequest(Collections.emptyMap());
            try ( RequestScoper.CloseableScope ignored = scope.open() ) {
                doTask();
            }
        }
    
        private void doTask() {
    
        }
    }
    

    Oh, and you probably will need some injections. Be sure to use providers there, you want to delay it's creation until inside the created scope.

提交回复
热议问题