2

I've simple Spring setup using @Inject, @ComponentScan and @EnableJpaRepositories. There is currently no need to have specific @Configurations for test, integration or production environments.

I'm now using the Spring test mvc framework and I'm introducing an @TestConfig containing mocked beans for my (Spring Data) Repository classes which also have the @Primary annotation. But the @EnableJpaRepositories seems not to obey to the @Primary for the repository beans in my TestConfig.

Is there an easy way to solve this or should I really split everything up using specific profiles not enabling Spring Data JPA repositories?

Oliver Drotbohm
  • 80,157
  • 18
  • 225
  • 211
Marcel Overdijk
  • 11,041
  • 17
  • 71
  • 110
  • Can you post stacktrace and configuration? One thing to take into account is that `@Primary` only works for beans which are detected by component-scanning for beans declared in xml it has to be declared in the xml configuration. In Java Config it has to be declared next to the @Bean annotation. – M. Deinum Oct 07 '13 at 10:40
  • I am not sure I get the use case here. `@Primary`'s purpose is to select one *implementation* as the primary one. As we deal with interfaces here, how can you actually get to two Spring beans in an `ApplicationContext` for an interface? However, if you use `@Primary` on a manually implemented stub, this bean instance should trump the proxy generated by `@EnableJpaRepositories`. – Oliver Drotbohm Oct 07 '13 at 20:00
  • Hi Oliver, The use case is I'm using a single (simple) Configuration class which also has the EnableJpaRepositories annotation. While executing my MVC tests (using the mvc test framework) I can't seem to mock my repositories. I tried creating a TestConfig with mocks for the repositories, but this does not work. – Marcel Overdijk Oct 08 '13 at 11:25
  • So how do you register the mock beans then? I'd assume an additional configuration class imported using `@Import`, containing `@Primary` `@Bean` methods should definitely trump the automatically registered ones. Also you could simply try naming the bean methods after the repository bean names. This should override the scanned ones as well. – Oliver Drotbohm Oct 14 '13 at 07:19
  • I'm having the same problem with Spring Boot's @ SpringBootApplication annotation. I'm not able to mock my repositories with @ Import and @ Primary @ Bean on the TestApplication class. Has anyone found a solution? – Mircea D. Aug 01 '16 at 08:38

0 Answers0