Search code examples
javaspring-bootclasspathcomponent-scan

Component Scan using application.properties in spring boot app


I made a java library that has component and configuration classes.

When I use the library in other spring boot services, the beans are not registered because the component and configuration classes are not in the classpath.

I know we can use @ComponentScan but I don't want to change the service's code. Is there a way of adding the classes to the classpath using application.properties? Or is there anything I can do in the library so that the beans get registered?


Solution

  • If you are using Spring Boot, you can take advantage of Spring Autoconfiguration.

    For that, you need to place a file spring.factories in META-INF/spring.factoriesin your library's .jar file. If you are using Gradle or Maven as a build tool and the standard folder structure, the file path is src/main/resources/META-INF/spring.factories.

    Here's an example from a library I wrote:

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    org.requirementsascode.spring.behavior.web.BehaviorConfiguration,\
    org.requirementsascode.spring.behavior.web.SerializationConfiguration,\
    org.requirementsascode.spring.behavior.web.BehaviorController
    

    As you can see, after the first, Spring specific line, you list all of your configuration classes.

    You can learn more about autoconfiguration here, for example.