依赖注入_set方法注入_构造器注入
生活随笔
收集整理的這篇文章主要介紹了
依赖注入_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方法注入_构造器注入的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringIOC容器介绍
- 下一篇: 依赖注入的细节_value子标签_特殊字