# 拓展方式注入(c、p命名空間) ###### tags: `Spring-DI` ## 拓展方式注入 我們可以使用p命名空間和c命名空間進行注入 ### 官方解釋 ![](https://i.imgur.com/RPuGEjY.png) ### 使用: ```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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--p命名空間注入,可以直接注入屬性的值:property--> <!--使用無參構造器--> <bean id="user" class="com.kuang.pojo.User" p:name="秦心" p:age="18"/> <!--c命名空間注入,通過構造器注入:construct--> <!--所以要有有參構造器--> <bean id="user2" class="com.kuang.pojo.User" c:age="18" c:name="戀戀"/> </beans> ``` ### 測試: ```java= @Test public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml"); User user = context.getBean("user2", User.class); System.out.println(user); } ``` ![](https://i.imgur.com/F51WKLv.jpg) ![](https://i.imgur.com/GdomMzV.jpg) ### 注意點: 1.p命名與c命名空間,不能直接使用,需要導入xml約束! ```xml= xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" ```