The @Autowired annotation helps us to connect constructors, fields, and setter functions. This annotation injects object dependencies.
Here's the sample code of how to use @Autowired on a property:
class User(val name: String,
val id: String)
class Users{
@Autowired
val user:User ?= null
}
Here's the sample code of how to use @Autowired on a property:
class UsersForAutowired{
private lateinit var userDetails: UserDetails
@Autowired
fun setUserDetails(userDetails: UserDetails){
this.userDetails = userDetails
}
fun getUserDetails(){
this.userDetails.getDetails()
}
}
The content of UserDetails.kt is as follows:
class UserDetails{
init {
println("This class has all the details of the user")
}
fun getDetails(){
println("Name: Naruto Uzumaki")
println("Village: Konohagakure")
}
}
The output of the project will be as follows:
This class has all the details of the user
Name: Naruto Uzumaki
Village: Konohagakure
We can utilize the @Autowired annotation on properties to dispose of the setter functions. When we pass values of autowired properties utilizing <property>, Spring will allocate those properties with the passed values or references. So with the utilization of @Autowired on properties, the UsersForAutowired.kt file will become as follows:
class UsersForAutowired{
init {
println("UsersForAutowired constructor." )
}
@Autowired
private lateinit var userDetails: UserDetails
fun getUserDetails(){
this.userDetails.getDetails()
}
}
The result will be as follows:
UsersForAutowired constructor.
This class has all the details of the user
Name: Naruto Uzumaki
Village: Konohagakure
You can also apply @Autowired to constructors. An @Autowired constructor annotation demonstrates that the constructor should be autowired when making the bean. This should be the case regardless of whether any <constructor-arg> components are utilized when configuring the bean in the XML file.
Here is the modified content of UsersForAutowired.kt:
class UsersForAutowired @Autowired constructor(private var userDetails: UserDetails) {
init {
println("UsersForAutowired constructor.")
}
fun getUserDetails() {
this.userDetails.getDetails()
}
}
The result will be as follows:
This class has all the details of the user
UsersForAutowired constructor.
Name: Naruto Uzumaki
Village: Konohagakure