在通过构造方法或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依赖注入的构造器注入