Search code examples
javaspringspring-bootautowiredcomponent-scan

How to create a Spring Library and consumers can import all the beans automatically?


I have created my own library and it has some code like this

package com.example.demo.service;

@Slf4j
@Service
@RequiredArgsConstructor
public final class MyCustomService {
...
}

package com.example.demo.config;

@Configuration
@ComponentScan(basePackages = "com.example.demo")
public class MyCustomConfig {
}

And I have pushed this library to artifact. Now in another app I am importing the above library in gradle and I am trying to use MyCustomService class but its not working and saying that a bean of type MyCustomService is not available. To make it work I added the below line in "consuming" app and now its working as expected.

@Configuration
@Import(MyCustomConfig.class)
public class AppConfig {}

But is there a way to include a library(my custom library) and then it should automatically register required beans and then work automatically without me having to import MyCustomConfig class again kinda like how other Spring libraries work(all we have to do is just include those deps in build.gradle).


Solution

  • If you use Spring Boot 2:

    • Create the file src/main/resources/META-INF/spring.factories in your library.
    • Add a key org.springframework.boot.autoconfigure.EnableAutoConfiguration with a value consisting of fully qualified class names of your auto-configuration classes, separated by commas.
    • In your case the file content has to be org.springframework.boot.autoconfigure.EnableAutoConfiguration=package com.example.demo.config.MyCustomConfig.

    If you use Spring Boot 3 (to be more precise >2.7):

    • Create the file src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports in your library.
    • List the fully qualified names of your auto-configuration classes in this file, placing each class on a separate line.
    • In your case the file content has to be package.com.example.demo.config.MyCustomConfig.
    • Annotate your configs with @AutoConfiguration (actually I don't do it and everything works, but better to follow what docs say)