Bean没有使用@Autowired注入

时间:2017-12-03 12:38:28

标签: java spring autowired

我在代码中做了一些@Autowired注释,我偶然发现了疑问。即使我没有在GetName.java中注入Employee bean,我的名字也是 John 。即使我没有使用任何注释自动装配它,bean也会被注入。在使用构造函数时是否需要记住一些特定的先决条件?

Employee.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();

}
}

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

如果Bean只有一个构造函数,Spring将进行构造函数注入,@Autowired注释可以省略。

请参阅https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-spring-beans-and-dependency-injection.html

此功能已添加了一个较新版本。