p命名空间和c命名空间

在通过构造方法或set方法给bean注入关联项时通常是通过constructor-arg元素和property元素来定义的。在有了p命名空间和c命名空间时我们可以简单的把它们当做bean的一个属性来进行定义。

p命名空间

使用p命名空间时需要先声明使用对应的命名空间,即在beans元素上加入

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

案例

<?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命名空间注入,可以直接注入属性的值:property-->
    <bean id=""user"" class=""com.yv.pojo.User"" p:name=""大恐龙"" p:age=""18""></bean>

</beans>

注意事项

在实体类 com.yv.pojo.User 中,需要有无参构造方法,否则会报错

p命名空间对应 Spring 依赖注入的 set 注入

c命名空间

使用c命名空间时需要先声明使用对应的命名空间,即在beans元素上加入

xmlns:c=""http://www.springframework.org/schema/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: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"">

    <!--C(构造: Constructor)命名空间 , 属性依然要设置set方法-->
    <bean id=""user2"" class=""com.yv.pojo.User"" c:name=""屿"" c:age=""18""/>
</beans>

注意事项

在实体类 com.yv.pojo.User 中,需要有参构造方法,否则会报错

C命名空间对应我们Spring依赖注入的构造器注入

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值