Spring通过setter方式注入失败的经历
实现的功能:
一个Person类,Student和Teacher是两个实现类,在老师类里面注入学类
代码如下
package com.test.one.charpterday1;
public interface Person {
public void Say();
}
package com.test.one.charpterday1;
public class Student implements Person {
@Override
public void Say() {
// TODO Auto-generated method stub
System.out.println("祝老师端午节安康");
}
}
package com.test.one.charpterday1;
public class Teacher implements Person {
private Student student;
public void setStudent(Student student) {
this.student=student;
}
@Override
public void Say() {
// TODO Auto-generated method stub
this.student.Say();
System.out.println("I am a goog teacher!!!");
}
}
package com.test.one.charpterdaytest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.test.one.charpterday1.Person;
import com.test.one.charpterday1.Student;
public class DayTest01 {
public static void main(String[] args) {
// // TODO Auto-generated method stub
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationcontext.xml");
Person teacher=(Person)applicationContext.getBean("teacher");
teacher.Say();
}
}
<?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 id="student" class="com.test.one.charpterday1.Student"/>
<!-- 往teacher类中注入学生类 -->
<bean id="teacher" class="com.test.one.charpterday1.Teacher"/>
<property name="student" ref="student"/>
</beans>
<!--运行后出现错误提示--lineNumber: 10; columnNumber: 42; cvc-complex-type.2.4.a: 发现了以元素 '{"http://www.springframework.org/schema/beans":property}' 开头的无效内容。
配置文件错误,原因是<bean 配置错误-->
正确的因为注入的Student实例要在Teacher的bean里面—如下所示–
以上就是本次错误经历!