-2

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.

mdo123
  • 1,757
  • 3
  • 16
  • 34
  • The note mentions the `RepositoryConfig` class, which is the target bean, and they are referring to its constructor. – Andreas Jun 16 '17 at 00:52
  • I'm confused about your misunderstanding. The quote says _`@Autowired` is not necessary on the `RepositoryConfig` constructor._ So `RepositoryConfig` is the bean (class) and, since it has a single constructor, doesn't require the `@Autowired` on that constructor. – Sotirios Delimanolis Jun 16 '17 at 00:53
  • as I said I'm a noob (which is why I was reading documentation). The "target bean" threw me off because a parameter of the RepositoryConfig constructor uses the Datasource bean. When you explain it - sure it makes sense now, but it didn't click for me. I tried to reproduce it but the code was not complete (although now I think about it I could test it with my own code) so I did make an effort to figure it out and did some searching online. I don't appreciate the down votes. I'm still not clear on what makes RepositoryConfig a bean, since the class has 3 annotations, is it any of them? – mdo123 Jun 16 '17 at 15:31

1 Answers1

1

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.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224