在 ApplicationContext.xml 中使用 <context:annotation-config /> 时自动装配注释不起作用

Autowired Annotation not working when uisng <context:annotation-config /> in ApplicationContext.xml

  <context:annotation-config />

当在 ApplicationContext.xml 文件中添加以上行时,Test.java 不是 运行 但是当我添加它时它有效但是在 tutorial 中我正在经历它说这两种方法都有效 有人可以帮助解决问题吗 以上代码行。

    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

Employee.java

    package com.stp.beans;

    import org.springframework.beans.factory.annotation.Autowired;

    public class Employee {
        private Address empaddress;

        public Address getEmpaddress() {
            return empaddress;
        }
        @Autowired
        public void setEmpaddress(Address empaddress) {
            this.empaddress = empaddress;
        }
    }

Address.java

    package com.stp.beans;

    public class Address {
        private String address;

        public String getAddress() {
            return address;
        }

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

ApplicationContext.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-4.3.xsd">
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
    <bean id ="empbean" class="com.stp.beans.Employee"></bean>
    <bean id ="adrbean" class="com.stp.beans.Address"></bean>
    </beans>

Test.java

    package com.stp.test;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    import com.stp.beans.Employee;

    public class Test {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("/com/stp/cfgs/ApplicationContext.xml");
            Employee emp = (Employee) context.getBean("empbean");
            System.out.println(emp.getEmpaddress());
        }
    }

当您使用 <context:annotation-config /> 时,您的 ApplicationContext.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:annotation-config />
<bean id ="empbean" class="com.stp.beans.Employee"></bean>
<bean id ="adrbean" class="com.stp.beans.Address"></bean>
</beans>

您刚刚错过了 context 相关定义。