1. 程式人生 > 其它 >Spring學習筆記-Bean

Spring學習筆記-Bean

Bean作用域(Bean Scope)

<!--顯式設定單例模式-->
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>
  • prototype【原型模式】:每個物件都有自己的bean
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>


request、session、application均只在web開發中使用到

Bean自動裝配

  • 自動裝配:Spring滿足Bean依賴的一種方式
  • Spring會在上下文中自動尋找並自動給bean裝配屬性

Spring中的三種裝配方式

  1. xml中顯式的配置
  2. java中顯式的配置
  3. 隱式的自動裝配【重點】

測試

  • 搭建環境
    • 新的普通Maven專案
    • 編寫實體類【一人有一貓一狗】
/**
 * @author Iris 2021/8/11
 */
public class Cat {

    public void shout() {
        System.out.println("Miao");
    }
}
public class Dog {

    public void shout() {
        System.out.println("Wang");
    }
}
public class Human {
    private Dog dog;
    private Cat cat;
    private String name;

    Setter&Getter
    toString();
}

ByName自動裝配實現

<!--
    byName:會自動在容器上下文中查詢,自己物件set方法後的值對應的bean-id
-->
<bean class="cn.iris.pojo.Human" id="human" autowire="byName">
    <property name="name" value="iris"/>
</bean>

ByType自動裝配實現

<!--
    byName:會自動在容器上下文中查詢,自己物件屬性型別相同的bean
-->
<bean class="cn.iris.pojo.Human" id="human" autowire="byType">
    <property name="name" value="iris"/>
</bean>

注意點

  • byName自動裝配時,id需與set方法後的值相同且唯一
  • byType自動裝配時,需保證屬性type唯一

註解實現自動裝配

註解開發不一定比xml配置更好,取決於使用者和使用情況
使用註解步驟:

  1. 匯入約束
<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

</beans>
  1. 配置註解的支援【手動高亮
<context:annotation-config/>

@Autowired

  • Autowired預設注入為byType,當同種型別數目>1時,再根據byName匹配注入
  • 【類屬性/set方法】上使用即可
  • 使用後可不寫set方法,前提:自動裝配的屬性在IoC容器中存在且符合byName
  • require(boolean)
    • false:顯式設定false說明該物件可為null;
    • true:物件不可為空
@Autowired
private Dog dog;
@Autowired
private Cat cat;

@Nullable

  • 被標記欄位可為null

@Qualifier

  • 新增物件id

@Resource

  • 預設byName匹配注入