I am working on some Java projects using Spring boot. I have an autoconfigured class MyAutoConfig
in the spring.factories
file in a project A
.
This configuration file has some bean definitions, for example the class Worker
.
The project B
is using A
as a library, in gradle like this:
implementation project(':project-A')
I can start project B
without any errors. But when I try to use @Autowired Worker worker
in project B
in the main class where I have @SpringBootConfiguration
, it told me that "expected at least 1 bean which qualifies as autowire candidate"
, so I assume that the bean is not in the context.
I would like to know what could be the problem ?
CodePudding user response:
Just found the solution. Instead of defining base packages to scan from separate library, I've just created configuration class inside this library with whole bunch of annotation and imported it to my main MyApplication.class:
package runnableProject.application;
import com.myProject.customLibrary.configuration.SharedConfigurationReference.class
@SpringBootApplication
@Import(SharedConfigurationReference.class)
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
package com.myProject.customLibrary.configuration;
@Configuration
@ComponentScan("com.myProject.customLibrary.configuration")
@EnableJpaRepositories("com.myProject.customLibrary.configuration.repository")
@EntityScan("com.myProject.customLibrary.configuration.domain")
public class SharedConfigurationReference {}
NOTE: However, if you want to avoid importing the configuration class. You can create a folder called 'META-INF' in the 'resources' folder of your library and add a file called 'spring.factories' with the content org.springframework.boot.autoconfigure.EnableAutoConfiguration=<fully_qualified_name_of_configuration_file> . This will autoconfigure your library
CodePudding user response:
@SpringBootConfiguration
is not enough for the auto-configuration. You should add @EnableAutoConfiguration
. This will trigger scanning spring.factories
files and do the rest for you.
Or using @SpringBootApplication
, because it has EnableAutoConfiguration
in it.
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication