-1

I am trying to autowire multiple services (around 10-15) in a class having static methods and came across a solution mentioned in this post about using @Autowired constructor. Can we use constructor @Autowired approach for multiple classes as well?

For example, suppose I have two classes Foo1 and Foo2. Can I use the single constructor for both classes like

@Component
public class Boo {

    private static Foo1 foo1;
    private static Foo2 foo2;

    @Autowired
    public Boo(Foo1 foo1, Foo2 foo2) {
        Boo.foo1 = foo1;
        Boo.foo2 = foo2;
    }

    public static void randomMethod() {
         foo1.doStuff();
         foo2.doSomeOtherStuff();
    }
}

Or is there any other way to achieve this ?

Bhagyesh Jain
  • 323
  • 2
  • 10
  • 1
    Yes you can, but it generally is a very bad idea, for one or two or any number of classes. Mutating the static field is a bad idea, there is no guarantee that the constructor is called before `randomMethod` is called, potentially causing a NPE. – luk2302 Mar 29 '19 at 11:32
  • @Bhagyesh do you know what 'static' is or does? the obvious answer here, is no – Stultuske Mar 29 '19 at 11:32
  • 1
    Also, having 10 to 15 dependencies in one class, is a clear indicator of a bad code structure. This violates the Single Responsibility Principle and will make it harder for you or your colleagues to maintain the code. – Tom Mar 29 '19 at 11:35

1 Answers1

0

Spring + static is a very bad idea.

I suggest making the randomMethod() not static and then inject Boo everywhere you earlier had to call the static method. E.g change this:

class A {
    public void run() {
        Boo.randomMethod();
    }
}

To this:

@Component
public class A {
    private final Boo boo;

    @Autowired
    public A(Boo boo) {
        this.boo = boo;
    }

    public void run() {
        boo.randomMethod();
    }
}

This construct is the spring intended way, and I suggest you to use it.

Lino
  • 19,604
  • 6
  • 47
  • 65