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:

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