0

I am developing a new feature that should be hidden behind a FeatureToggleX. As part of that, I need to add a new dependency b to my SomeClass:

class SomeClass {

  private OldDependency a;
  private NewDependency b;

  @Autowired
  public SomeClass(OldDependency a, NewDependency b) {
    this.a = a;
    this.b = b;
  }

}

I use a custom IfActive annotation as Conditional that serves TheToggledDependency if, and only if, FeatureToggleX is active:

@Component
@IfActive("FeatureToggleX")
class TheToggledDependency implements NewDependency {
}

How can I make Spring temporarily wire b = null while FeatureToggleX is off?

Is there a clean way to plug a generic solution into Spring's wiring process that detects IfActive components and supplies nulls in their places?


  • As recommended in other answers, I considered @Autowired(required = false) - maybe in combination with overloading SomeClass's constructor - to allow omitting b, but this has the side effect that it also legalizes omitting a, which should be an error.

  • I could provide an alternative dummy IfInactive variant of NewDependency, but that would fill my project with worthless dummies that I need to remember removing when the toggle is removed.

  • Similarly, I could build two variants of SomeClass, one that has NewDependency and a second that is completely unaware of it, and choose between the two depending on the toggle. However, that is impractical for larger classes because it duplicates other, unaffected functionality.

Florian
  • 4,821
  • 2
  • 19
  • 44
  • You might want to have a look at SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(Object target, ServletContext sc). You can autowire any dependencies in your annotation processor. – Sachin Kumar Dec 20 '18 at 09:50

1 Answers1

1

No, at least not in the constructor. One way to deal with this kind of things is setter injection.

So you would have something like this (duck-typing here):

class SomeClass {


  private OldDependency a;
  private NewDependency b;

  @Autowired
  public SomeClass(OldDependency a) {
    this.a = a;
  }

  @Autorired(required=false)
  public void setNewDependency(NewDependency b) {
   this.b = b;
  }

}

I hope this helps.

Stefa
  • 656
  • 5
  • 13