# 拓展方式注入(c、p命名空間) ###### tags: `Spring-DI` ## 拓展方式注入 我們可以使用p命名空間和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 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); } ```   ### 注意點: 1.p命名與c命名空間,不能直接使用,需要導入xml約束! ```xml= xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up