Spring入門系列-依賴注入
依賴注入
概念
- 依賴注入
- 依賴:指的是Bean物件的建立依賴於容器,Bean物件的依賴資源
- 注入:指的是Bean物件所依賴的資源,由配置容器來設定和裝配
Set注入
要求被注入的屬性,必須要有set方法,set方法的方法名是由set+屬性首字母大寫,如果屬性是boolean型別,1沒有set屬性,是is
測試pojo類 :
Address.java
package com.dreamcold.demo.pojo; public class Address { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
Student.java
package com.dreamcold.demo.pojo; import java.util.*; public class Student { private String name; private Address address; private String[] books; private List<String> hobbys; private Map<String,String> card; private Set<String> games; private String wife; private Properties info; public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public String[] getBooks() { return books; } public void setBooks(String[] books) { this.books = books; } public List<String> getHobbys() { return hobbys; } public void setHobbys(List<String> hobbys) { this.hobbys = hobbys; } public Map<String, String> getCard() { return card; } public void setCard(Map<String, String> card) { this.card = card; } public Set<String> getGames() { return games; } public void setGames(Set<String> games) { this.games = games; } public String getWife() { return wife; } public void setWife(String wife) { this.wife = wife; } public Properties getInfo() { return info; } public void setInfo(Properties info) { this.info = info; } public void show(){ System.out.println("name="+ name + ",address="+ address.getAddress() + ",books=" ); for (String book:books){ System.out.print("<<"+book+">>\t"); } System.out.println("\n愛好:"+hobbys); System.out.println("card:"+card); System.out.println("games:"+games); System.out.println("wife:"+wife); System.out.println("info:"+info); } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", address=" + address + ", books=" + Arrays.toString(books) + ", hobbys=" + hobbys + ", card=" + card + ", games=" + games + ", wife='" + wife + '\'' + ", info=" + info + '}'; } }
常量注入
<bean id="student" class="com.dreamcold.demo.pojo.Student">
<property name="name" value="xiaoming"></property>
</bean>
測試
package com.dreamcold.demo; import com.dreamcold.demo.pojo.Student; import org.junit.jupiter.api.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class HelloTest { @Test public void test(){ ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml"); //我們的物件都在Spring中管理 Student student=(Student)context.getBean("student"); System.out.println(student); } }
Bean的注入
注意點:這裡的值是一個引用,ref
<?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-3.0.xsd">
<bean id="student" class="com.dreamcold.demo.pojo.Student">
<property name="name" value="xiaoming"></property>
<property name="address" ref="addr"></property>
</bean>
<bean id="addr" class="com.dreamcold.demo.pojo.Address">
<property name="address" value="ChongQing"></property>
</bean>
</beans>
陣列的注入
<?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-3.0.xsd">
<bean id="student" class="com.dreamcold.demo.pojo.Student">
<property name="name" value="xiaoming"></property>
<property name="address" ref="addr"></property>
<property name="books">
<array>
<value>西遊記</value>
<value>紅樓夢</value>
<value>水滸傳</value>
</array>
</property>
</bean>
<bean id="addr" class="com.dreamcold.demo.pojo.Address">
<property name="address" value="ChongQing"></property>
</bean>
</beans>
List注入
<?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-3.0.xsd">
<bean id="student" class="com.dreamcold.demo.pojo.Student">
<property name="name" value="xiaoming"></property>
<property name="address" ref="addr"></property>
<property name="books">
<array>
<value>西遊記</value>
<value>紅樓夢</value>
<value>水滸傳</value>
</array>
</property>
<property name="hobbys">
<list>
<value>
聽歌
</value>
<value>
看電影
</value>
<value>
爬山
</value>
</list>
</property>
</bean>
<bean id="addr" class="com.dreamcold.demo.pojo.Address">
<property name="address" value="ChongQing"></property>
</bean>
</beans>
Map注入
<?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-3.0.xsd">
<bean id="student" class="com.dreamcold.demo.pojo.Student">
<property name="name" value="xiaoming"></property>
<property name="address" ref="addr"></property>
<property name="books">
<array>
<value>西遊記</value>
<value>紅樓夢</value>
<value>水滸傳</value>
</array>
</property>
<property name="hobbys">
<list>
<value>
聽歌
</value>
<value>
看電影
</value>
<value>
爬山
</value>
</list>
</property>
<property name="card">
<map>
<entry key="中國郵政" value="1234567"></entry>
<entry key="建設銀行" value="1223334"></entry>
</map>
</property>
</bean>
<bean id="addr" class="com.dreamcold.demo.pojo.Address">
<property name="address" value="ChongQing"></property>
</bean>
</beans>
Set注入
<?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-3.0.xsd">
<bean id="student" class="com.dreamcold.demo.pojo.Student">
<property name="name" value="xiaoming"></property>
<property name="address" ref="addr"></property>
<property name="books">
<array>
<value>西遊記</value>
<value>紅樓夢</value>
<value>水滸傳</value>
</array>
</property>
<property name="hobbys">
<list>
<value>
聽歌
</value>
<value>
看電影
</value>
<value>
爬山
</value>
</list>
</property>
<property name="card">
<map>
<entry key="中國郵政" value="1234567"></entry>
<entry key="建設銀行" value="1223334"></entry>
</map>
</property>
<property name="games">
<set>
<value>LOL</value>
<value>王者榮耀</value>
<value>吃雞</value>
</set>
</property>
</bean>
<bean id="addr" class="com.dreamcold.demo.pojo.Address">
<property name="address" value="ChongQing"></property>
</bean>
</beans>
NULL值注入
<property name="wife">
<null></null>
</property>
Properties注入
<property name="info">
<props>
<prop key="姓名">小明</prop>
<prop key="性別">男</prop>
<prop key="學號">123355</prop>
</props>
</property>
測試結果
p命名和c命名注入
User.java :【注意:這裡沒有有參構造器!】
package com.dreamcold.demo.pojo;
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
1、P名稱空間注入 : 需要在標頭檔案中加入約束檔案
匯入約束 : xmlns:p="http://www.springframework.org/schema/p"
<bean id="user" class="com.dreamcold.demo.pojo.User" p:name="yujian" p:age="12">
</bean>
2、c 名稱空間注入 : 需要在標頭檔案中加入約束檔案
匯入約束 : xmlns:c="http://www.springframework.org/schema/c"
<bean id="myuser" class="com.dreamcold.demo.pojo.User" c:name="yujian" c:age="12">
</bean>
發現問題:爆紅了,剛才我們沒有寫有參構造!
解決:把有參構造器加上,這裡也能知道,c 就是所謂的構造器注入!
測試程式碼:
package com.dreamcold.demo;
import com.dreamcold.demo.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloTest {
@Test
public void test(){
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
//我們的物件都在Spring中管理
User user=(User)context.getBean("myuser");
System.out.println(user);
}
}
Bean的作用域
在Spring中,那些組成應用程式的主體及由Spring IoC容器所管理的物件,被稱之為bean。簡單地講,bean就是由IoC容器初始化、裝配及管理的物件 .
幾種作用域中,request、session作用域僅在基於web的應用中使用(不必關心你所採用的是什麼web應用框架),只能用在基於web的Spring ApplicationContext環境。
Singleton
當一個bean的作用域為Singleton,那麼Spring IoC容器中只會存在一個共享的bean例項,並且所有對bean的請求,只要id與該bean定義相匹配,則只會返回bean的同一例項。Singleton是單例型別,就是在建立起容器時就同時自動建立了一個bean的物件,不管你是否使用,他都存在了,每次獲取到的物件都是同一個物件。注意,Singleton作用域是Spring中的預設作用域。要在XML中將bean定義成singleton,可以這樣配置:
<bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">
測試:
@Test
public void test03(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User) context.getBean("user");
User user2 = (User) context.getBean("user");
System.out.println(user==user2);
}
Prototype
當一個bean的作用域為Prototype,表示一個bean定義對應多個物件例項。Prototype作用域的bean會導致在每次對該bean請求(將其注入到另一個bean中,或者以程式的方式呼叫容器的getBean()方法)時都會建立一個新的bean例項。Prototype是原型型別,它在我們建立容器的時候並沒有例項化,而是當我們獲取bean的時候才會去建立一個物件,而且我們每次獲取到的物件都不是同一個物件。根據經驗,對有狀態的bean應該使用prototype作用域,而對無狀態的bean則應該使用singleton作用域。在XML中將bean定義成prototype,可以這樣配置:
<bean id="account" class="com.foo.DefaultAccount" scope="prototype"/>
或者
<bean id="account" class="com.foo.DefaultAccount" singleton="false"/>
Request
當一個bean的作用域為Request,表示在一次HTTP請求中,一個bean定義對應一個例項;即每個HTTP請求都會有各自的bean例項,它們依據某個bean定義建立而成。該作用域僅在基於web的Spring ApplicationContext情形下有效。考慮下面bean定義:
<bean id="loginAction" class=cn.csdn.LoginAction" scope="request"/>
針對每次HTTP請求,Spring容器會根據loginAction bean的定義建立一個全新的LoginAction bean例項,且該loginAction bean例項僅在當前HTTP request內有效,因此可以根據需要放心的更改所建例項的內部狀態,而其他請求中根據loginAction bean定義建立的例項,將不會看到這些特定於某個請求的狀態變化。當處理請求結束,request作用域的bean例項將被銷燬。
Session
當一個bean的作用域為Session,表示在一個HTTP Session中,一個bean定義對應一個例項。該作用域僅在基於web的Spring ApplicationContext情形下有效。考慮下面bean定義:
<bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>
針對某個HTTP Session,Spring容器會根據userPreferences bean定義建立一個全新的userPreferences bean例項,且該userPreferences bean僅在當前HTTP Session內有效。與request作用域一樣,可以根據需要放心的更改所建立例項的內部狀態,而別的HTTP Session中根據userPreferences建立的例項,將不會看到這些特定於某個HTTP Session的狀態變化。當HTTP Session最終被廢棄的時候,在該HTTP Session作用域內的bean也會被廢棄掉。
學習自連結:狂神說