c:construct 构造器注入
p:property 属性注入
c命名空间注入和p命名空间注入都属于第三方注入,需要引入xml依赖
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
案例:
1.创建pojo类
package com.web.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private String name;
private int age;
private Address address;
}
2.创建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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- p命名空间 -->
<bean id="address" class="com.web.pojo.Address" p:address="西安"/>
<bean id="teacher1" class="com.web.pojo.Teacher" p:name="alis" p:age="23" p:address-ref="address"/>
<!-- c命名空间 -->
<bean id="teacher2" class="com.web.pojo.Teacher" c:name="sim" c:age="21" c:address-ref="address"/>
</beans>
3.测试
package com.web.test;
import com.web.pojo.Teacher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.annotations.Test;
public class TestTeacher {
@Test
public void testTeacher1(){
ApplicationContext context=new ClassPathXmlApplicationContext("Teacher.xml");
Teacher bean = context.getBean("teacher1",Teacher.class);
System.out.println(bean);
}
@Test
public void testTeacher2(){
ApplicationContext context=new ClassPathXmlApplicationContext("Teacher.xml");
Teacher bean = context.getBean("teacher2",Teacher.class);
System.out.println(bean);
}
}
Teacher(name=alis, age=23, address=Address(address=西安))
Teacher(name=sim, age=21, address=Address(address=西安))