日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

依赖注入_set方法注入_构造器注入

發布時間:2024/4/13 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 依赖注入_set方法注入_构造器注入 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

屬性注入

屬性注入即通過 setter 方法注入Bean 的屬性值或依賴的對象

屬性注入使用 <property> 元素, 使用 name 屬性指定 Bean 的屬性名稱,value 屬性或 <value> 子節點指定屬性值?

屬性注入是實際應用中最常用的注入方式

?

構造方法注入

通過構造方法注入Bean 的屬性值或依賴的對象,它保證了 Bean 實例在實例化后就可以使用。

構造器注入在 <constructor-arg> 元素里聲明屬性, <constructor-arg> 中沒有 name 屬性

?

<?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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 配置Car, 屬性注入(set方法注入) --><bean id="car" class="com.learn.spring.beans.Car"><property name="brand" ><value>Audi</value></property><property name="crop" value="yiqi"></property><property name="price" value="400000"></property></bean><!--配置Car,構造器注入value:指定注入的值index:指定構造器參數的位置type:指定構造器參數的類型.--><bean id="car1" class="com.learn.spring.beans.Car"><constructor-arg value="BMW"></constructor-arg><constructor-arg value="500000" index="2" type="double"></constructor-arg><constructor-arg value="huachen" index="1"></constructor-arg></bean><bean id="car2" class="com.learn.spring.beans.Car"><constructor-arg value="Benz"></constructor-arg><constructor-arg value="300" index="2"></constructor-arg><constructor-arg value="msds" index="1"></constructor-arg></bean> </beans> package com.learn.spring.test;import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;import com.learn.spring.beans.Book; import com.learn.spring.beans.Car; import com.learn.spring.beans.HelloWorld; import com.learn.spring.beans.Person; import com.learn.spring.beans.PersonList; import com.learn.spring.beans.PersonMap;public class Main {public static void main(String[] args) { //獲取Car對象.Car car = (Car)ctx.getBean("car");System.out.println(car);car = (Car)ctx.getBean("car1");System.out.println(car);car = (Car)ctx.getBean("car2");System.out.println(car); } }

?

總結

以上是生活随笔為你收集整理的依赖注入_set方法注入_构造器注入的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。