There are 3 ways you can create an instance using @Autowired
.
1. @Autowired
on Properties
The annotation can be used directly on properties, therefore eliminating the need for getters and setters:
@Component("userService")
public class UserService {
public String getName() {
return "service name";
}
}
@Component
public class UserController {
@Autowired
UserService userService
}
In the above example, Spring looks for and injects userService
when UserController
is created.
2. @Autowired
on Setters
The @Autowired
annotation can be used on setter methods. In the below example, when the annotation is used on the setter method, the setter method is called with the instance of userService
when UserController
is created:
public class UserController {
private UserService userService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
}
3. @Autowired
on Constructors
The @Autowired
annotation can also be used on constructors. In the below example, when the annotation is used on a constructor, an instance of userService
is injected as an argument to the constructor when UserController
is created:
public class UserController {
private UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService= userService;
}
}