0
  <context:annotation-config />

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

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

雇员.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;
        }
    }

地址.java

    package com.stp.beans;

    public class Address {
        private String address;

        public String getAddress() {
            return address;
        }

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

应用程序上下文.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>

测试.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());
        }
    }
4

1 回答 1

2

当您使用时<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相关定义。

于 2018-08-07T11:34:29.177 回答