Mitesh Joshi
Mitesh Joshi

Reputation: 185

How does Spring dependency injection work inside a class that is annotated @Component but any without constructor annotation?

My code is working but I'm not able to figure from where I'm getting dependency injection. As Spring documentation mentions nothing about default dependency injection.

package org.stackoverflow; 


@Component 
public class A {
    private final B b;
    public A(B b) {
      this.b = b;
    }
}

package org.segfault; 


@Configuration
Public class Config {
   @Bean 
   public B b(){ return new B(); }
}

As in above code component scan is running on the path com.stackoverflow and imported org.segfault class config. But as you can see there no constructor injection in class A.

I suspect it must be documented somewhere. But I'm not able to find out. Anyway, it's working :)

Can someone help with documentation or Is there anything that I'm missing?

Upvotes: 0

Views: 60

Answers (2)

LppEdd
LppEdd

Reputation: 21134

Since Spring 4.3.*, specifying the @Autowire annotation above the constructor isn't needed anymore, provided that there is a single, non-private constructor for the class.

6.1 Core Container Improvements (news)
It is no longer necessary to specify the @Autowired annotation if the target bean only defines one constructor.

Upvotes: 1

Andreas
Andreas

Reputation: 159096

The Spring documentation, chapter 17. Spring Beans and Dependency Injection says:

If a bean has one constructor, you can omit the @Autowired

Upvotes: 2

Related Questions