我在代码中做了一些 @Autowired 注释,我偶然发现了一个疑问。尽管我没有在 GetName.java 中注入(inject) Employee bean,但我得到的名称为 John。尽管我没有使用任何注释 Autowiring bean,但它还是被注入(inject)了。使用构造函数时是否需要牢记一些特定的先决条件?
员工.Java
package com.sample.employee;
public class Employee {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
GetName.java
package com.sample.salary;
import org.springframework.beans.factory.annotation.Autowired;
import com.sample.employee.Employee;
public class GetName {
// @Autowired
public Employee emp;
// @Autowired
public GetName(Employee emp) {
this.emp = emp;
}
public void displayName() {
System.out.println(emp.getName()); //prints John
}
}
spring.xml
<?xml
version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
xmlns:context="http://www.springframework.org/schema/context">
<context:annotation-config />
<!-- <context:component-scan base-package="com.sample.employee"/> -->
<bean id="empl" class="com.sample.employee.Employee">
<property name="name" value="John" />
</bean>
<bean id="GetNames" class="com.sample.salary.GetName"/>
</beans>
MainClass.java
package com.sample.employee;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sample.salary.SalaryCalculator;
public class MainCLass {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
GetName cal = (GetName) context.getBean("GetNames");
cal.displayName();
}
}
我错过了什么吗?
最佳答案
如果一个Bean只有一个构造函数,Spring会进行构造函数注入(inject),@Autowired
注解可以省略。
此功能是在最新版本之一中添加的。
关于java - Bean 在不使用 @Autowired 的情况下被注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47618428/