Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not autowire bean in test class

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 ?

like image 298
YLombardi Avatar asked Nov 10 '22 04:11

YLombardi


1 Answers

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 })
like image 80
Miguel Pereira Avatar answered Dec 05 '22 11:12

Miguel Pereira