Spring - 基于c命名空间的注入

作用与优势:

  1. 简化配置:使用c命名空间可以直接在XML配置中以属性赋值的形式传递构造函数参数,而不需要使用繁琐的<constructor-arg>标签。

  2. 提高可读性:配置文件变得更加简洁易读,尤其是在需要传递多个构造函数参数时,c命名空间可以大大减少配置的冗余。

  3. 减少冗余代码:对于构造函数注入,传统的XML配置中需要使用<constructor-arg>标签,c命名空间提供了更短、更直接的配置方式。

  • 传统的Spring 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>"
       xsi:schemaLocation="<http://www.springframework.org/schema/beans> <http://www.springframework.org/schema/beans/spring-beans.xsd>">
       
    <bean id="peopleBean" class="com.powernode.spring6.bean.People">
        <constructor-arg name="name" value="zhangsan"/>
        <constructor-arg name="age" value="18"/>
        <constructor-arg name="sex" value="true"/>
    </bean>
</beans>
  • 基于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:c="<http://www.springframework.org/schema/c>"
       xsi:schemaLocation="<http://www.springframework.org/schema/beans> <http://www.springframework.org/schema/beans/spring-beans.xsd>">
        <bean id="peopleBean" class="com.powernode.spring6.bean.People" c:_0="zhangsan" c:_1="18" c:_2="true"/>

</beans>

总结:

  • 和p命名空间注入一样,不过针对的是对构造函数参数的配置。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值