0

i've use the following configuration:

@Profile("database")
@Configuration
@EnableJpaRepositories(basePackages = "com.example.repository")
public class RepositoryConfig {
}
public interface MyRepositoryInterface extends PagingAndSortingRepository<MyEntity, Long> {
 // ...
}

Which creates a PagingAndSortingRepository repository. As you may see, this is only created when the "database" profile is active. There are several other repros that are activated with other profiles.

Now I want to create a talking error message in case no repository was created (e.g. by using a wrong profile).

The first thought was this: @Profile("!database & !filesystem ...") However, this is too cumbersome for many profiles and requires maintenance.

Therefore, the next thought was the following:

@Configuration
public class OnMissingRepository {

    @ConditionalOnMissingBean(MyRepositoryInterface.class)
    @Bean
    public MyRepositoryInterface missingBean() {
        throw new IllegalArgumentException("You forgot to specify a profile");
    }
}

Unfortunately, @EnableJpaRepositories does not seem to create the repository bean until after @ConditionalOnMissingBean has been evaluated. I get the above exception every time.

Is there a way to implement this here?

Thanks!

INJG
  • 71
  • 7
  • Wouldn't the application blow up anyway without repositories? If there are no repositories I would expect some services to fail. The `@Conditional` will not work as those are evaluated very early on. Your only hope might be a `BeanPostProcessor` that checks for beans implementing `Repository` (the most toplevel tagging interface of Spring Data) if none of those are available throw an exception. – M. Deinum Dec 16 '20 at 11:39
  • That is correct, the application will not start because Spring cannot resolve a dependency. But the error message is too unspecific and can refer to anything, which is why I wanted to give a hint about the profiles. But thanks for the answer. – INJG Dec 16 '20 at 12:17
  • That error is generally quite specific about which bean is missing. There is even an exception analyzer which makes that message clearer. – M. Deinum Dec 16 '20 at 12:35

0 Answers0