Spring命名空间注入

62 篇文章 1 订阅
60 篇文章 0 订阅

p命名空间设置注入


对于设置注入与构造注入,在配置文件中,除了使用<property><constructor-arg>标签外。还可以使用命名空间注入的方式,让注入的值以<bean/>标签的属性的方式出现,根据注入实现方式的不同,分为P命名空间注入与C命名空间注入

p命名空间注入:

采用设值注入方式,故需要bean有相应的setter方法

c命名空间注入:

采用构造注入方式,故需要有相应的构造器

修改配置文件头,添加相应的约束

p命名空间注入需要添加的约束

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

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"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 学校依旧使用设置注入 -->
    <bean id="mySchool" class="com.hk.spring.di03.School">
        <property name="schloolName" value="红林小学"/>
    </bean>
    <!-- p命名空间设值注入 -->
    <bean id="myStudent" class="com.hk.spring.di03.Student" p:name="小华" p:age="8" p:school-ref="mySchool">
    </bean>
</beans>


c命名空间注入需要添加的约束

 xmlns:c="http://www.springframework.org/schema/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: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="mySchool" class="com.hk.spring.di04.School">
        <property name="schloolName" value="红林小学"/>
    </bean>
    <bean id="myStudent" class="com.hk.spring.di04.Student" c:name="小林" c:age="8" c:school-ref="mySchool">
    </bean>
</beans>


其实这些约束是可以在你解压的Spring中的spring-framework-4.2.1.RELEASE-dist\spring-framework-4.2.1.RELEASE\docs\spring-framework-reference\html\index.html


CTRL+Fp-namespace,检索到的第一条记录就有p命名空间注入约束

这里写图片描述


CTRL+Fc-namespace,检索到的第一条记录就有c命名空间注入约束

这里写图片描述

要点

除了要添加相应的约束之外,设值注入bean一定要有set方法,构造注入一定要有构造方法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值