浅谈Spring6之P和C命名空间注入的区别

时间:2021-12-28 00:52:38

基于P命名空间注入

P命名空间注入是简化构造方法的注入
使用P命名空间注入的两个条件
一:xmlns:p="http://www.springframework.org/schema/p"
二:提供set方法
class类

浅谈Spring6之P和C命名空间注入的区别

Spring_p.xml配置

<!--P命名注入底层是set注入>
<bean id="dogBean" class="com.spring6.bean.Dog " p:name="like" p:age="2" p:birth-ref="birthBean"></bean>
<!-- 获取当前系统时间-->
<bean id="birthBean" class="java.util.Date"></bean>

浅谈Spring6之P和C命名空间注入的区别

浅谈Spring6之P和C命名空间注入的区别

测试类
//p注入
@Test
public void pset(){
ApplicationContext p = new ClassPathXmlApplicationContext("SpringConfig_p.xml");
Dog dogBean = p.getBean("dogBean", Dog.class);
System.out.println(dogBean.toString());
}

基于c命名空间注入

C命名空间注入是简化构造方法的注入
使用C命名空间注入的两个条件
一:xmlns:c="http://www.springframework.org/schema/c"
二:提供构造方法
Class类

浅谈Spring6之P和C命名空间注入的区别

Spring.xml配置

xmlns:c="http://www.springframework.org/schema/c"

<bean id="peopleBean" class="com.spring6.bean.People" c:_0="张三" c:_1="20" c:_2="true"></bean>
测试类
//C注入
@Test
public void cset(){
ApplicationContext c = new ClassPathXmlApplicationContext("SpringConfig_c.xml");
People peopleBean = c.getBean("peopleBean", People.class);
System.out.println(peopleBean.toString());
}

浅谈Spring6之P和C命名空间注入的区别

浅谈Spring6之P和C命名空间注入的区别

浅谈Spring6之P和C命名空间注入的区别