Search code examples
springspring-bootkotlindependency-injectionreactive-programming

ReactiveCrudRepository is not found by Spring to be injected into other classes


Problem:

I have a ReactiveCrudRepository which I want to use in a RestController but it's not found by Spring to be injected anymore. Before I refactored the repository towards becoming reactive (it was a CrudRepository before) the repository was found and injected by Spring.

Now I get this error:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in de.shinythings.microservices.core.product.services.ProductServiceImpl required a bean of type 'de.shinythings.microservices.core.product.persistence.ProductRepository' that could not be found.


Action:

Consider defining a bean of type 'de.shinythings.microservices.core.product.persistence.ProductRepository' in your configuration.

The repository looks like this: link to GitHub

interface ProductRepository : ReactiveCrudRepository<ProductEntity, String> {

    fun findByProductId(productId: Int): Mono<ProductEntity>
}

The rest controller looks like this: link to GitHub

@RestController
class ProductServiceImpl(
        private val repository: ProductRepository,
        private val mapper: ProductMapper,
        private val serviceUtil: ServiceUtil
) : ProductService { // implementation left out here }

What I tried so far:

I enabled the debug flag in my application.yml to learn more from the output but this did not generate useful insights.

I removed the ProductRepository dependency from the ProductServiceImpl class to not get the above error when starting up Spring.

Then I wrote myself a little test to ask the ApplicationContext for the ProductRepository specifically:

@SpringBootTest
class BeanLoadingDebugging {

    @Autowired
    private lateinit var applicationContext: ApplicationContext

    @Test
    fun test() {
        val bean = applicationContext.getBean(ProductRepository::class.java)

        Assert.notNull(bean, "Bean not found!")
    }
}

This also does not work!

So it seems that this repository just does not want to be found. I double-checked this and tried the same with the not reactive CrudRepository and this was found. 🤷‍♂️

Full disclosure:

I'm new to Spring / Spring Boot and happy for any advice here.

The complete code can be found on GitHub.


Solution

  • First, You have to update the dependency from org.springframework.boot:spring-boot-starter-data-mongodb to org.springframework.boot:spring-boot-starter-data-mongodb-reactive.

    Second, enable reactive support like below,

    @SpringBootApplication
    @ComponentScan("de.shinythings")
    @EnableReactiveMongoRepositories 
    class RecommendationServiceApplication
    

    After these two changes i can see the test de.shinythings.microservices.core.recommendation.BeanLoadingDebugging success.

    Look more into Spring reactive mongo