目录
一、p命名空间注入
p命名空间注入简化的是set方法注入
创建测试类:
@Data
@ToString
public class PTest {
private String name;
private Integer age;
private Date birth;
}
第一步添加p命名空间
第二步使用p:属性名 = 赋予属性的值
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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="pBean" class="com.cjc.spring6.bean.PTest" p:name="小明" p:age="12" p:birth-ref="date"/>
<!--获取当前系统时间-->
<bean id="date" class="java.util.Date"/>
</beans>
测试代码:
@Test
public void getP(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("pBean.xml");
PTest pBean = applicationContext.getBean("pBean", PTest.class);
System.out.println(pBean);
}
测试结果:
二、c命名空间注入
c命名空间注入是基于构造方法实现的。
创建测试类:
@AllArgsConstructor
@ToString
@Data
public class CTest {
private String name;
private Integer age;
}
创建spring.xml核心配置文件并进行相关配置
添加c命名空间
使用并给相关属性赋值
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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="cBean" class="com.cjc.spring6.bean.CTest" c:name="老王" c:age="18"></bean>
</beans>
测试代码:
@Test
public void getC(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("CBean.xml");
CTest cBean = applicationContext.getBean("cBean", CTest.class);
System.out.println(cBean);
}
测试结果: