Spring boot rest controller in auto configuration library

110 views Asked by At

I'm writing a spring boot library with autoconfiguration.

What it means is that I dont put any @Component/@Service and dont rely on class path scanning, instead I have a @AutoConfiguration class that is loaded with the AutoConfiguration.imports file.

Everything works fine, except, I want my library to include a @RestController as well. Now, if I just annotate it with @RestController, it will be picked up by component scanning.. But if I don't annotate it, it doesnt work as a RestController. (it will be registered as a bean but the rest endpoints will throw 404 because the web mvc processor will ignore it since it's not annotated).

How can I achieve my purpose? Thanks

1

There are 1 answers

6
Ruslan Zinovyev On

You can try to design your auto-configuration to conditionally register your controller bean. Once they need it, they simply set a param in application.properties and a bean will be created. In this scenario, the existence of @RestController annotation shouldn't be a problem.

@Configuration
@ConditionalOnProperty(name = "nameOfYourLibrary.enable-controller", havingValue = "true")
public class LibraryAutoConfiguration {
    @Bean
    public Controller myController() {
        return new Controller();
    }
}

Update: Alternatively you can try to exclude your bean from component scanning:

@SpringBootApplication
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = MyController.class))
public class SpringApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringApplication.class, args);
    }

    @Bean
    public MyController myController() {
        return new MyController();
    }
}

You also can read this article, maybe it will provide some tips where to dig further: how to create a controller based on auto configuration spring boot 1.4.0