1. 程式人生 > 其它 >Spring中 bean 配置檔案中的標籤使用

Spring中 bean 配置檔案中的標籤使用

技術標籤:Spring框架springbean

import 標籤 匯入其他的Bean配置檔案

  • resource :其他Bean配置檔名

bean 標籤 管理物件

  • id :物件名

  • class : 物件的模板類(spring底層是通過反射例項化物件)

  • name : 起別名(可以起多個別名,多個別名之間用 逗號、空格或者“;”符號隔開。<s1、s2、s3、s4都可以訪問>)

  • parent : 當前bean 複製 IoC 容器中的其他bean 但是要當前 bean class 模板中要有 其他bean 模板的所有成員變數

  • depends-on : 依賴關係 被依賴的 bean

    優先建立 (Spring 作用域Scope 預設是單例singleton的,單例模式下當bean.xml 檔案載入時,就會建立bean 物件。)

  • scope : bean作用域

    scope
    singleton單例,表示通過 IoC 容器獲取的 bean 是唯一的
    prototype原型,表示通過 IoC 容器獲取的 bean 是不同的
    request請求,表示在一次 HTTP 請求內有效
    session會話,表示在一次使用者會話內有效
  • property 標籤 使用無參構造get、set方法建立物件

    • name : 成員變數名
    • value : 成員變數值(基本資料型別String可以直接賦值,其他資料型別不能使用value,要使用ref)
    • ref : 將IoC中的另外一個Bean賦值給當前的成員變數 (DI 依賴注入
    • index : 使用下標匹配
  • constructor-arg 標籤 使用有參構造方式建立物件
    (name、value、ref 和 index)和 property 標籤中的一樣

alias 標籤 起別名

  • name : 其他 bean的id名
  • alias : 自己取的別名
<?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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<import resource="Spring-AOP.xml"/> <bean id="gogo" class="com.cl.pojo.Student" name="s1,s2 s3;s4" scope="singleton" > <property name="id" value="1"/> <property name="name" value="小號"/> <property name="addresses" ref="address"/> </bean> <bean id="stu" class="com.cl.pojo.Student"> <constructor-arg name="id" value="1"/> <constructor-arg name="name" value="小裡"/> <constructor-arg name="addresses" ref="address"/> </bean> <bean id="address" class="com.cl.pojo.Address"> <property name="id" value="1"></property> <property name="address" value="迎風路"></property> </bean> <bean id="address01" class="com.cl.pojo.Address" parent="address"></bean> <alias name="gogo" alias="student"/> </beans>

在這裡插入圖片描述