接上文中的springFrameWork 第三章:setter注入器注入文章:
引入 “setter注入器的P标签和C标签注入” 可以简化代码量
需要在xml配置文件中进行引入添加 P标签和C标签 :
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
即将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"
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-4.3.xsd">
<!-- 属性setter注入 P标签 -->
<bean id="userModel" class="com.ioc.UserModel" p:id="zhm123" p:name="zhm" p:sex="man"></bean>
<bean id="userService" class="com.ioc.UserService" p:userModel-ref="userModel"></bean>
</beans>
需要注意的是 在P标签中,如果是 常量类型 就 p: name ="xxxx" 的结构 , 如果是对象引用类型则是: p:userModel-ref="userModel"
第二种简化标签的方法是:C标签
还可以使用构造器中的C标签,也需要修改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"
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-4.3.xsd">
<!-- 构造方法注入 C标签 -->
<bean id = "userModel" class = "com.ioc.UserModel" c:id="zqw111" c:name="zqw" c:sex="woman"></bean>
<bean id = "userService" class = "com.ioc.UserService" c:userModel-ref="userModel"></bean>
</beans>
调用展示的效果和上面效果一样:
常量:c:id="zqw111" c:name="zqw" c:sex="woman"
引用: c:userModel-ref="userModel"