Based on the example being followed here : https://dzone.com/articles/autowiring-in-spring
import org.springframework.stereotype.Component;
@Component
public class Department {
private String deptName;
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
}
The @Autowired annotation is placed on the Department.
import org.springframework.beans.factory.annotation.Autowired;
public class Employee {
private int eid;
private String ename;
@Autowired
private Department department; //<----------------------
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public void showEmployeeDetails(){
System.out.println("Employee Id : " + eid);
System.out.println("Employee Name : " + ename);
System.out.println("Department : " + department.getDeptName());
}
}
This runs the program.
public class RunThis {
public static void main(String[] args)
{
System.out.println("Hello World");
Employee emp = new Employee();
emp.showEmployeeDetails();
}
}
Running the program results in a NULL exception which is expected, but per the provided URL, it reads :
@Autowired on Properties
In the below example, when the annotation is directly used on properties, Spring looks for and injects Department when Employee is created.
As a result, I interpreted to mean that the Department object would implicitly be instantiated behind the scenes at the time the Employee object is instantiated, but apparently that is wrong.
1 - How can this sample be modified to view the actual benefits of the @Autowired annotation?
Many other examples discuss the @Autowired annotation affecting what is written to some XML file in my project.
I searched my project for all files and don't see any reference toward the object (Department) other than Employee and Department.
2 - Where is the XML file located that one can view the changes affected by the use of the @Autowired annotation?
I think you're missing the bigger picture. You annotate classes so that they're managed by Spring. In order to use Spring you'll have to adapt your main.
@SpringBootApplication
public class RunThis {
public static void main(String[] args)
{
SpringApplication.run(RunThis.class, args);
System.out.println("Hello World");
Employee emp = new Employee();
emp.showEmployeeDetails();
}
}
Now our project is managed in Spring but our Employee isn't as we make this.
We should let Spring handle this by creating a bean for our employee and fetching that bean. The creation of beans we do in classes annotated in @Configuration
or via a ComponentScan.
Also all your changes when it comes to annotating won't be vissible in any .xml file.