Search code examples
spring-bootgraphqljavabeansspring-boot-test

Springboot with Graphql error with "Consider defining a bean of type '{component name}' in your configuration."


I am using Spring boot with graphql and rest. While adding graphql component I used annotation like this.

Controller

@Controller // <------ with this annotation
@EnableAutoConfiguration
class AController( 
    @Autowired val aRepository: ARepository,
    @Autowired val aService: AService
){
 ...
}

Service

@Service // <------ with this annotation
class AService (
{
 ...
}

Repository

@GraphQlRepository
interface ARepository: JpaRepository<A, Long> {

But got these errors

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type '{component name}' in your configuration.

It only happens when using test

@WebMvcTest
@AutoConfigureMockMvc
internal class ControllerTest {
    @Test
    @WithMockUser
    fun healthCheck() {
        mockMvc.perform(get("/api/v1/healthcheck"))
            .andExpect(status().isOk).andExpect(
                content().string("healthy")
            ).andDo(print())
    }
}

I understand I can use ComponentSacn but I want to know why this happend. Because this package was place along with other components witch @ComponentScanner works well.

My structure is like this. material works well while it cannot scan bakeryReview enter image description here

I think I used component annotations okay, and package structure is okay. 😭 Maybe test is the problem?


Solution

  • My bad!! 😂 There's nothing wrong with annotation nor structure. For those who see this question, It was WebMvcTest. WebMvcTest needs component to be mocked, because it only injects web-related components like @Controller. So it omits other components like @Service or @Repository.

    I added these and it works okay.

    @MockBean
    lateinit var aService: AService
    
    @MockBean
    lateinit var aRepository: ARepository