p命名空间和c命名空间

本文介绍了Spring框架中p和c命名空间的使用。p命名空间用于属性注入,简化了XML配置文件中属性设置的过程;而c命名空间则用于构造器注入,允许直接在bean定义中指定构造函数参数。通过这两个命名空间,可以更方便地管理实体类的依赖注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

p命名空间

  • 实体类中必须有set方法;
  • 实体类中必须有无参构造器(默认存在);
  • 导入p命名空间注入方式依赖。
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    <bean id="demo1" class="com.Demo1" p:dog="小黄"/>
    <bean id="helloWorld" class="com.HelloWorld" p:a="a" p:b="b" p:demo1-ref="demo1"/>
    <!--等同于-->
    <!--<bean id="helloWorld" class="com.HelloWorld">-->
    <!--    <property name="a" value="a"/>-->
    <!--    <property name="b" value="b"/>-->
    <!--    <property name="demo1" ref="demo1"/>-->
    <!--</bean>-->
</beans>

c命名空间

  • 实体类中必须存在有参构造器;
  • 导入c命名空间注入方式依赖。
<?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:util="http://www.springframework.org/schema/util"
       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
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    <bean id="demo1" class="com.Demo1" p:dog="小黄"/>
    <bean id="helloWorld" class="com.HelloWorld" c:a="a" c:b="b" c:demo1-ref="demo1"/>
    <!--等同于-->
    <!--<bean id="helloWorld"  class="com.HelloWorld">-->
    <!--    <constructor-arg  index="0"  value="a"></constructor-arg>-->
    <!--    <constructor-arg  index="1"  value="b"></constructor-arg>-->
    <!--    <constructor-arg  index="2"  ref="demo1"></constructor-arg>-->
    <!--</bean>-->
</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值