I know this compiles, but my question is, is it a good idea? I'm mostly curious about why it might NOT be a good idea. Even better, is there an alternative, if SomeStaticClass is a @Component, but it also must be a static member of MyComponent. My understanding is that its poor design to have Spring autowire static members. Based on what I've read, I still don't quite understand why. Say I have the following:
@Component
public final class MyComponent {
private static SomeStaticClass someStaticClass;
@Autowired
MyComponent(SomeStaticClass someStaticClass) {
MyComponent.someStaticClass = someStaticClass;
}
}
Few reasons why it's a bad design:
static mutable fields are a bad design in general
makes testing harder - once this field is set, it will remain set in the next test, possibly creating hidden interdependency
what if you want to have two instances of MyComponent, each with different SomeStaticClass? Chaos.
you cannot inject values via static field or setter autowiring, it's explicitly forbidden. There must be a reason for that.
why do you even need that? Do you have static methods in MyComponent? Why?
if the above is true, how do you prevent calling MyComponent.staticMethod() before the constructor initialized that field? The whole point of Spring is to return fully populated, safe beans
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With