基于此处遵循的示例: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;
}
}
@ Autowired批注放置在部门上。
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());
}
}
这将运行程序。
public class RunThis {
public static void main(String[] args)
{
System.out.println("Hello World");
Employee emp = new Employee();
emp.showEmployeeDetails();
}
}
运行程序会导致出现NULL异常,但是,根据提供的URL,它显示为:
@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.
结果,我的解释是,在实例化Employee对象时,将在后台隐式实例化Department对象,但是显然这是错误的。
1-如何修改此示例以查看@Autowired注释的实际好处?
[许多其他示例讨论了@Autowired注释,这些注释会影响在我的项目中写入某些XML文件的内容。
我在我的项目中搜索了所有文件,除Employee和Department之外,没有看到对该对象(部门)的任何引用。
2-XML文件位于哪里,可以查看使用@Autowired注释影响的更改?
我认为您错过了更大的前景。您注释类,以便它们由Spring管理。为了使用Spring,您必须调整主语言。
@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();
}
}
现在我们的项目在Spring进行管理,但我们的雇员不是我们这样做的。我们应该让Spring通过为员工创建一个bean并获取该bean来处理此问题。我们在@Configuration
或通过ComponentScan注释的类中创建bean。
此外,在注释中的所有更改都不会在任何.xml文件中显示。
您没有将部门设置为任何东西,因为部门是一种pojo,要从自动装配中受益,最好在Spring Boot加载的配置类中执行类似以下的操作
@Bean
public Department department () {
Department department = new Department ();
department.setDeptName("foo");
return department;
}
尽管您提供了链接,但我什至没有关注它,因为它显示了它们使用XML配置Bean,您尚未执行此操作,因此自动装配将不起作用。