I have a library jar which I want to provide to a number of applications. The behavior I want is to create a common spring component class in the library. If in the applications, the same component is not extended then use the common component; if it's extended in the app, then use the extended component (child class). Is this possible? - Create CommonComponent only if a child for that class doesn't exist.
I am using Java 1.8, Springboot2.0
Created class in library:
@Component
public class CommonComponent{}
In one of the child apps using the library, I added a child component:
@Component
public class ChildComponent extends CommonComponent{}
I expected one component ChildComponent created; but in the above scenario 2 components - CommonComponent and ChildComponent are created.
One way you could do this is to take advantage of the @ConditionalOnMissingBean
annotation that Spring Boot has. When combined with a bean definition in a @Configuration
class, we can tell Spring to only define our bean if it doesn't already have one.
This is untested:
@Configuration
public class CustomComponentConfiguration {
@ConditionalOnMissingBean(CustomComponent.class)
@Bean
public CustomComponent customComponent() {
return new CustomComponent();
}
}
In this example, when our @Configuration
runs, Spring determines if there is any other bean that is a CustomComponent
. If not, it executes the customComponent()
method and defines whatever bean you return. So if somebody else defines a ChildComponent
, this method will not get called.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments