I have a project with Spring MVC and Spring Boot and I use IntelliJ. My Project is like this :
main -> java -> mypackage -> authentification -> WebSecurityConfig.java
-> configuration -> ApplicationConfiguration.java
-> controller -> WelcomeMessageController.java
-> service -> WelcomeMessageService.java
-> Impl -> WelcomeMessageServiceImpl.java
test -> java -> mypackage -> WelcomeMessageTest.java
I annotate the service implementation with @Service
.
I annotate the configuration file with
@Configuration
@ComponentScan(basePackages = "mypackage")
In the controller, I inject the service with
@Autowired
WelcomeMessageService welcomeMessageService;
In the test class, I inject the same service with the same annotation:
@Autowired
WelcomeMessageService welcomeMessageService;
I annotate the test class with :
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationConfiguration.class, loader = SpringApplicationContextLoader.class)
@WebAppConfiguration
In the controller, the injection works fine but in the test class, IntelliJ says:
Could not autowire. No beans of type WelcomeService found.
When I run the test it works, but I don't understand why IntelliJ says that it can't find the bean.
I found this topics that says that it happens some time with IntelliJ but I don't want to use the @SuppressWarnings
annotation.
Does anyone have another solution to solve this problem ?
For me it was a component scan issue my models are in a separate module then my Spring Boot App. Normally, @SpringBootApplication has a @ComponentScan which when not specified will scan as follows:
Either {@link #basePackageClasses} or {@link #basePackages} (or its alias * {@link #value}) may be specified to define specific packages to scan. If specific * packages are not defined, scanning will occur from the package of the * class that declares this annotation.
If your SpringBootApp Main class is on a different package then you want to specify the ComponentScan. Same thing if you are using multiple modules, specify it on your Configuration class.
Config class Annotations:
@Configuration
@ComponentScan(basePackages = "app.data")
Testclass Annotations:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { PropertyPlaceholderAutoConfiguration.class, DynamoConfig.class })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With