For example, if I have a UserService that has a dependency on UserRepository, I can have the UserRepository injected using @Autowired annotation like this:
UserRepository Class...
class UserRepository { UserRepository () {} }
UserService Class...
class UserService { @Autowired private UserRepository userRepository; UserService () {} }
This is done using Field Injection. The same thing can be accomplied using Setter Injection:
class UserService { private UserRepository userRepository; UserService () {} @Autowired // Using setter injection public void setUserRepository( UserRepository userRepository) { this.userRepository = userRepository } }
or via Constructor Injection:
class UserService { private UserRepository userRepository; @Autowired // Using constructor Injection UserService (UserRepository userRepository) { this.userRepository = userRepository } }
There are different opinions on which method is "the right way" but since this post is not about that debate. I would point you to this post instead: Why I changed My Mind About Field Injection
Which ever method you choose to use, you are essentially doing the same thing: instructing Spring to supply an object's dependency by using the @Autowired annotation.
But what happens when the Object you want injected in has a constructor that requires an argument?