Spring boot auto configuration with dependency and without @ComponentScan

后端 未结 2 1145
一整个雨季
一整个雨季 2021-02-09 14:56

Spring boot provides @ComponentScan to find packages to be scanned.

I am building a library which has @RestControllers inside with package com

相关标签:
2条回答
  • 2021-02-09 15:03

    Spring boot starter are special artifacts designed by Spring and used by Spring.
    You can check that in the source code that contains mainly a
    spring.provides file :

    provides: spring-boot-actuator,micrometer-core

    I don't know the exact way to process in the same way as Spring Boot Starter but as probably acceptable workaround, you could define in your jar a @Configuration class that specifies @ComponentScan("com.mylib").

     @Configuration
     @ComponentScan("com.mylib")
     public class MyLibConfig {
         //...
     }
    

    In this way, clients of the jar need "only" to import the @Configuration class :

    @Import(MyLibConfig.class)
    @Configuration
    public class ClientConfig{
      //...
    }
    
    0 讨论(0)
  • 2021-02-09 15:29

    You could create a Spring Boot Starter in the same style as the Spring Provided Starters. They are essentially a jar'd library with a a spring.factories file pointing to the @Configuration class to load with some other annotations on there to provide overriding/bean back off (@ConditionalOnMissingBean) and generally provide their own @ConfigurationProperties.

    Stéphane Nicoll provided an excellent demo of how to build one.

    https://github.com/snicoll-demos/hello-service-auto-configuration

    It is also documented in the Spring Boot documentation. https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-auto-configuration.html

    The library approach would also work but I see no benefit in not making it a starter. Additionally for any library/starter I'd recommend dropping the @ComponentScan and just defining the beans in a @Configuration. This will work for sterotypes like @RestController etc. will function as normal if you create an @Bean out of it in a configuration.

    0 讨论(0)
提交回复
热议问题