Search code examples
javaspringautowiredspring-annotations

How to understand the spring reference documentation regarding @Autowired


Hopefully this question is simple enough. I'm reading the Spring Framework Reference:beans-java section and I came across this usage example enter image description here

The part that confuses me is the note at the end, specifically where it says

Note also that there is no need to specify @Autowired if the target bean defines only one constructor; in the example above, @Autowired is not necessary on the RepositoryConfig constructor.

I don't quite understand why I can remove @Autowired from RepositoryConfig()? What is the target bean in this case and what constructor are they referring to?

I attempted to reproduce this but the documentation doesn't provide the AccountRepository class or the TransferService class and I'm a noob so not sure what they should like look. So a reproducible example would be desirable.


Solution

  • Spring version before 4.3 required you to annotate the constructor you wanted to use with @Autowired. Even if your class had a single constructor.

    As of Spring 4.3 when your class has a single constructor you can leave out the @Autowired on the constructor as Spring then automatically assumes you want to use that constructor.

    See this blog for more information and here the Jira ticket.