feybas
feybas

Reputation: 173

Does autowiring the constructor cause Spring to create at least one instance of that object?

I an looking at code that assigns an object to a static reference via autowiring of the constructor:

@Component
class MySpringClass {
  private static PaymentRepo paymentRepo;

  @Autowired
  MySpringClass(PaymentRepo repo) { MySpringClass.paymentRepo = repo; }

  static void usePaymentRepoToDoStuff() { …. using paymentRepo ….. }
}

I've read that assigning static references via autowiring is not recommended. I didn't do it. Not my code.

I can't find a place where even one instance of MySpringClass is explicitly created (but this is a lot of code). This code works reliably.

So, does @Autowired cause Spring to create at least one instance of MySpringClass, and thus the constructor to run, even if never explicitly called for in Java? Otherwise, I'll keep looking and trying to figure this out. thanks.

Upvotes: 0

Views: 965

Answers (2)

Ivan
Ivan

Reputation: 8758

It depends on whether your Spring container configured with default lazy initialization of beans (by default is is eager, not lazy). So by default Spring will create instance of a bean upon creation of Spring context. And since you are using Spring you do not need to check if code uses constructor directly since Spring will create bean and you should not create objects marked as beans using constructor (this eliminates the whole concept of dependency injection and inversion of control).

In case of lazy loading configured Spring will create bean only when it is needed.

Upvotes: 1

Dan Serb
Dan Serb

Reputation: 155

@Component declared on the class, is going to be read by Spring and it's going to be instantiated as a Spring Bean (by default, is going to be a Singleton, so just one instance) and it's going to be added to the Spring Application Context. Also you can then use the MySpringClass all over the application if you @Autowired it.

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/stereotype/Component.html

Upvotes: 1

Related Questions