0
点赞
收藏
分享

微信扫一扫

Spring命名空间注入

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+F​​​p-namespace​​​,检索到的第一条记录就有p命名空间注入约束

Spring命名空间注入_xml


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

Spring命名空间注入_xml_02

要点

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


举报

相关推荐

0 条评论