1

My @Configuration defines a couple of beans - A & B

@Configuration
public class MyConfiguration {

    @Bean
    public A supplyA() {
        return new A(...);
    }

    @Bean
    public B supplyB() {
        return new B(...);
    }
}

I was expecting that I should @Autowire A and B where they are needed, like so:

@Controller
public MyController {

    @Autowire
    public MyController(A a, B b) {

    }
}

But it does work fine without the @Autowire on the constructor. What gives? (I'm on Spring 5 if that matters)

Keerthi
  • 466
  • 6
  • 12
  • 5
    Starting with Spring 4.3, if a class, which is configured as a Spring bean, has only one constructor, the @Autowired annotation can be omitted and Spring will use that constructor and inject all necessary dependencies. https://stackoverflow.com/questions/41092751/spring-injects-dependencies-in-constructor-without-autowired-annotation – Marc Stroebel May 05 '20 at 10:20
  • Thanks. That explains. – Keerthi May 05 '20 at 13:48

1 Answers1

0

I think what you're trying is constructor injection, check https://docs.spring.io/spring/docs/4.3.26.RELEASE/spring-framework-reference/htmlsingle/#beans-constructor-injection

@Autowire, normally used for set injection.

Please understand the difference, before you make a change

PatrickChen
  • 1,350
  • 1
  • 11
  • 19