0

I have an application build via Spring Boot and using JAX-RS (Jersey). For JAX-RS resources Spring DI works fine but for sub-resources - not. I will provide examples below:

Sub-resource:

@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class InjuryResource {

    @Autowired 
    private InjuryRepository injuryRepository;
    @Autowired
    private AthleteRepository athleteRepository;

    // logic goes here

}

If I call this class as a sub-resource from parent resource like this :

@Path("/athletes")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class AthleteResource {

    // other logic

    @Path(ATHLETE_ID_PATH + INJURIES_PATH)
    public InjuryResource getInjuryResource() {
        return new InjuryResource();
    }


}

Then non of the repositories are injected into these resource, if I use it as basic resource then injection works fine.

I have tried this solution and checked it via debugger that dependencies are set to InjuryResource but it did not help (when the request is made repositories point to null in this resource, however, I saw that they were injected):

@Configuration
public class InjuryResourceConfig {

    @Autowired
    private AthleteRepository athleteRepository;
    @Autowired
    private InjuryRepository injuryRepository;

    @Bean
    public InjuryResource createBean() {
        InjuryResource injuryResource = new InjuryResource();
        injuryResource.setAthleteRepository(athleteRepository);
        injuryResource.setInjuryRepository(injuryRepository);
        return injuryResource;
    }
}

As I understood it correctly, Spring does not control life cycle of sub-resources in JAX-RS? If it is true then how could be repositories injected into the sub-resource?

Appreciate your help!

Maksim
  • 351
  • 1
  • 2
  • 12
  • 1
    https://stackoverflow.com/questions/38428397/java-spring-jersey-subresource-inject-constructor-arg-at-runtime – Toerktumlare Apr 26 '20 at 00:13
  • 1
    Tes, Thomas's link is correct. If you instantiate the resource, you're taking Jersey out of the lifecycle process. When you use ResourceContext and pass the class, Jersey takes control of the lifecycle which includes the injection. – Paul Samsotha Apr 26 '20 at 04:49
  • 1
    Also remove `@Path("/")` from your subresource classes. If you do any kind of scanning for for resources, it will get picked up and registered. It is not required. – Paul Samsotha Apr 26 '20 at 04:50

0 Answers0