Home > Enterprise >  Spring: Prioritize component if present
Spring: Prioritize component if present

Time:10-20

I have three components with the same superclass, all of them conditional on property. I want to autowire JUST ONE of the components, prioritizing in a specific order. I thought of using @Order, but I wonder if it can be used in this scenario or just to order a collection of those components?

Components

@Component
@ConditionalOnProperty("stable.enabled")
public class StableChild extends ParentClass {}
@Component
@ConditionalOnProperty("experimental.enabled")
public class ExperimentalChild extends ParentClass {}
@Component
@ConditionalOnProperty("testing.enabled")
public class TestingChild extends ParentClass {}

How I intend to use

@Component
public class WhateverClass {

  /**
   * I want to autowire TestingChild if it is present, otherwise ExperimentalChild. If it
   * is also not present, then StableChild. If all of them are absent it is okay to throw 
   * the exception because something is wrong with the configurations.
   */
  @Autowired
  private ParentClass component;
}

CodePudding user response:

I don't think you need @Order here. All you need to do is to use Conditional Of Missing bean

  • Related