首先使用p或c标签注入需要导入约束
在xml文件上方加入
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
p命名标签可以给属性传值,相当于property
c命名标签可以给参数传值,相当于constructor-arg
实体类中写入无参构造和有参构造
public Student() {
}
public Student(String name) {
this.name = name;
}
配置文件中写入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
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.xsd">
<bean id="student" class="pojo.Student" p:name="李佳琪"/>
<bean id="student1" class="pojo.Student" c:name="李佳琪1"/>
</beans>
测试类
@Test
public void myTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
Student student1 = context.getBean("student1", Student.class);
System.out.println(student);
System.out.println(student1);
}
测试结果与预想结果一致