Question

I can make an object visible to my Jersey resources by making it a property of the Application (or ResourceConfig)

This doesn't work:

public class MyResource {
    @Context private Application app;
    private SomeType thing;

    public MyResource() {
         thing = (SomeType) app.getProperties().get("thing"); // NullPointerException
    }
}

... because evidently the injection does not happen until after the constructor has run.

This does work:

public class MyResource {
    @Context private Application app;
    private SomeType thing;

    @GET
    @Path("foo")
    public AnotherType get() {
         thing = (SomeType) app.getProperties().get("thing"); // NullPointerException
         ...
    }
}

But it seems inelegant to have a step to get that property at the start of every method (even if it's a call to a lazy initialization method).

Is there some other way I can make a method run after the constructor but before any @GET/@POST/etc methods are called?

Was it helpful?

Solution

@PostConstruct is your friend.

As long as your class is registered with Jersey, a method annotated with @PostConstruct will be called after the the class is instantiated and the injections are completed and before any service calls are executed.

This isn't called out specifically in the Jersey docs that I'm aware of but there are some mentions of it on Google. It does make sense since with any injection framework, injections need to occur after object creation and they all use the @PostConstruct annotation to provide a place to do initialization after injection is complete.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top