@Autowired不适用于XML配置Spring

时间:2019-07-11 09:59:44

标签: spring dependency-injection

我有一个简单的beans.xml文件,如下所示。

它有两个bean:

员工和 地址

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    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">

    <bean id="address" class="com.atul.test.Address"></bean> 

    <bean id="employee" class="com.atul.test.Employee"> 
    </bean>

</beans>

我有以下Java类和配置。

public class Employee {

    @Autowired
    private Address address;

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public void checkAddress(){

        System.out.println("Your address is = "+this.address);
        this.address.vomit();


    }   
}
public class Address {

    public void vomit(){
        System.out.println("Vomit !!!!");
    }

}
public class App 
{
    public static void main( String[] args )
    {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        Employee employee = (Employee)ctx.getBean("employee");

        System.out.println("Employee = "+employee);
        Address address = (Address)ctx.getBean("address");
        System.out.println("address = "+address);

        System.out.println("employee.address = "+employee.getAddress());

    }
}

问题:

  1. 尽管如此,我在 Employee 班上有@Autowired地址没有被注入

  2. 我得到employee.address为NULL

  3. ctx.getBean("employee")ctx.getBean("address")都返回正确的bean (non null)

  4. 根据我的理解,只要@Autowired中的两个bean都可用,Spring context就应该起作用,在这种情况下,这是真的

2 个答案:

答案 0 :(得分:1)

您的Spring XML需要<context:annotation-config/>才能启用Spring注释。

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context = "http://www.springframework.org/schema/context"
   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">

    <context:annotation-config/>

    <bean id="address" class="com.atul.test.Address"></bean>

    <bean id="employee" class="com.atul.test.Employee"></bean>

</beans>

答案 1 :(得分:-1)

您必须在课程地址上使用@Component

@Component
public class Address {

    public void vomit(){
        System.out.println("Vomit !!!!");
    }

}

您必须在要与自动装配一起使用的所有类上使用@Component