Spring does not inject dependencies in JAX-RS defined sub-resource

38 Views Asked by At

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!

0

There are 0 best solutions below