Using @Context, @Provider and ContextResolver in JAX-RS

前端 未结 5 1276
感情败类
感情败类 2020-12-02 15:35

I\'m just getting acquainted with implementing REST web services in Java using JAX-RS and I ran into the following problem. One of my resource classes requires access to a s

5条回答
  •  眼角桃花
    2020-12-02 16:14

    A pattern that works for me: Add some fields on your Application subclass that provide the objects you need to inject. Then use an abstract base class to do the "injection":

    public abstract class ServiceBase {
    
        protected Database database;
    
        @Context
        public void setApplication(Application app) {
            YourApplication application = (YourApplication) app;
            database = application.getDatabase();
        }
    }
    

    All your services that need to access the database may now extend ServiceBase and have the database available automatically via the protected field (or a getter, if you prefer that).

    This works for me with Undertow and Resteasy. In theory this should work across all JAX-RS implementations since injection of the Application is supported by the standard AFAICS, but I haven't tested it in other settings.

    For me, the advantage over Bryant's solution was that I don't have to write some resolver class just so I can get at my application-scoped singletons like the database.

提交回复
热议问题