Issue
I have written a common library for future SpringBoot applications and made it into a jar
. Inside, there is a service that autowires an interface:
@Service
public class MyService {
protected @Autowired AbstractUserService abstractUserService;
}
public interface AbstractUserService {
Optional<? extends AbstractUser> findByPrincipal(Principal principal);
}
In my main application, in build.gradle
I load the library mentioned above as follows:
...
repositories {
flatDir {
dirs "$rootDir/libs"
}
}
...
dependencies {
...
implementation name: "my-library"
...
}
Then I have implemented the interface:
@Service
public class UserService implements AbstractUserService {
@Override public Optional<? extends AbstractUser> findByPrincipal(Principal principal) {
// do something
}
However, it seems that the library is unable to find it and I get the following exception:
Parameter 1 of constructor in MyService required a bean of type 'AbstractUserService' that could not be found.
In my main application I have also added the following annotation in order to @Autowire
the services exposed by this library:
@SpringBootApplication(scanBasePackages = {"the.root.package.of.my-library"})
Is there something that can be done? Also, is there a better way of autowiring the exposed services without the explicit scanBasePackage
description?
Solution
I have managed to fix it.
First, I have removed the explicit scanBasePackage
description from @SpringBootApplication
.
Secondly, I have annotated the configuration file from the library with @ComponentScan
and created the following file: resources/META-INF/spring.factories
with the following content:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
my-library.package.MyLibraryConfig
This is my complete library config file:
@Configuration
@ComponentScan
public class MyConfig {
...
}
Answered By - Mihai Catalin Valentin
Answer Checked By - Marilyn (JavaFixing Volunteer)