Spring Webflux R2DBC: When is EnableR2dbcRepositories required?

Viewed 30

I am learning Spring Webflux. In some code samples they add a org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories annotation to the main class [example]

@SpringBootApplication
@EnableR2dbcRepositories
public class SpringReactiveApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringReactiveApplication.class, args);
    }
}

and in others they don't [example]. I have tried it both ways with no difference in the result. So I am trying to understand when do we need this annotation and when we don't?

There is another annotation that I have seen some examples use and other's don't. That is org.springframework.stereotype.Repository. In some examples [e.g.] I see:

@Repository
public interface CustomerRepository extends
        ReactiveCrudRepository<Customer, Long> {

others don't use it. so asking same question for this annotation as well.

1 Answers

@SpringBootApplicaton is the combination of @EnableAutoConfiguration, @ComponentScan and @Configuration annotations.

@EnableAutoConfiguration enables Spring Boot's auto-configuration mechanism.

By annotating classes/interfaces with @Repository annotation we make clasess/interfaces available for auto-detection during auto-configuration. Therefore, by default Spring Boot tries to guess the location of @Repository definitions as long as the interfaces are located in the same package or sub-package.

But if the repositories are outside of SpringReactiveApplication located package we need register repository beans to the context using @EnableR2dbcRepositories. We will also get more control by using the @EnableR2dbcRepositories.

For the interfaces that extend ReactiveCrudRepository it's not necessary to put @Repository annotation on them. Because Spring Boot recognizes the repositories by the fact that they extend one of the predefined Repository interfaces.

Related