P名称空间注入(用的不多,但是也是一种方式)
目录
第一步:添加p 名称空间在配置文件中(和上面的xmlns区别就在于最后的beans和p)
(1)使用P名称空间注入,可以简化基于xml 配置方式
首先,我们先来看看初始的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">
</beans>
P名称空间注入的前提:
修改xmlns中的约束条件:
第一步:添加p 名称空间在配置文件中(和上面的xmlns区别就在于最后的beans和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"
<!--添加p名称空间在配置文件中-->
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">
</beans>
(2)进行属性注入,在<bean>标签里面进行操作
其次,我们先来看看初始的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">
<!--配置Book对象创建-->
<bean id="book" class="com.lbj.spring5.Book">
<!--使用property完成属性注入
name:类里面的属性名称
value:向属性注入的值
-->
<property name="bname" value="红楼梦"></property>
</bean>
</beans>
第二步:用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">
<!--配置Book对象创建-->
<!--使用p标签简化注入-->
<bean id="book" class="com.lbj.spring5.Book" p:bname="红楼梦">
</bean>
</beans>
测试结果: