ConditionalOnMissingBean and hierachical starters



I have two kinds of applications, one is a special case of the other and so I have two layers of starters, where one starter is providing a basic functionality for the more general application type and the other for the more specific type of application. The specific one inherits the behavior of the more general one and then modifies it according to its own needs.

I have the following components:
SA – starter for the general application (jar).
SAP – starter parent for general application with SA as dependency and some other dependencies (pom).
SCA – “child” starter, with SAP as parent (jar).
SCAP – “child” starter parent for the more specific apps with dependency to SCA and some further dependencies (pom).

General apps use SAP as their parent and specific apps use SCAP as their parent.

I want to define a bean in SCA that will replace a bean in SA. For this I put ConditionalOnMissingBean in auto configuration in SA and created a bean with the same name in SCA but I get BeanDefinitionOverrideException. I don’t want to use primary, as I plan on adding this ConditionalOnMissingBean also on that bean from SCA.

How do I approach this? Is the hierarchy of starters/starter parents appriopriate?

Answer

It sounds like you need to use @AutoConfigureBefore and/or @AutoConfigureAfter on your auto-configuration classes in conjunction with @ConditionalOnMissingBean.

The auto-configuration in your child starters should be ordered before the auto-configuration in the parent. Any beans that the child may want to replace should be defined in the parent with @ConditionalOnMissingBean. This arrangement will allow the child starter to define beans first. When the auto-configuration in the parent is then processed it will back off where beans have already been defined.

Note that for this to work, you must be using auto-configuration classes declared in spring.factories. This is described in more detail in this section of the Spring Boot reference documentation.



Source: stackoverflow