<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());
}
}
答案 0 :(得分:0)
使用<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
相关的定义。