Search code examples
javaspring-bootjersey

Spring Boot: Jersey ResourceConfig needs annotating?


I am just getting started with Spring Boot and I wanted to implement a ResourceConfig and I finding some conflicting ideas.

Take the following:

@Component
public class JerseyExampleConfig extends ResourceConfig {

The above is annotated with COMPONENT:

@Configuration
public class JerseyExampleConfig extends ResourceConfig {

Which one is correct?

I thought annotating with Configuration would be the correct way but it appears that the Component is used in examples.

What's the difference?


Solution

  • The documentation suggests @Component:

    To get started with Jersey 2.x just include the spring-boot-starter-jersey as a dependency and then you need one @Bean of type ResourceConfig in which you register all the endpoints:

    @Component
    public class JerseyConfig extends ResourceConfig {
    
        public JerseyConfig() {
            register(Endpoint.class);
        }
    }
    

    The documentation also says the following:

    You can also register an arbitrary number of beans implementing ResourceConfigCustomizer for more advanced customizations.

    All the registered endpoints should be @Components with HTTP resource annotations (@GET etc.), e.g.

    @Component
    @Path("/hello")
    public class Endpoint {
    
        @GET
        public String message() {
            return "Hello";
        }
    }
    

    Since the Endpoint is a Spring @Component its lifecycle is managed by Spring and you can @Autowired dependencies and inject external configuration with @Value. The Jersey servlet will be registered and mapped to /* by default. You can change the mapping by adding @ApplicationPath to your ResourceConfig.