国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

7、spring 依賴注入(DI)

2019-11-08 02:51:45
字體:
來源:轉載
供稿:網友

7、sPRing 依賴注入(DI)

在spring框架中,主要有以下四種依賴注入的方式

setter方法注入構造器注入靜態方法注入

實例工廠注入

在實際的運用中主要使用前兩種,所以在本文中也主要介紹前兩種DI方式


示例1:setter方法依賴注入

目錄結構如下: 這里寫圖片描述

配置文件bean.xml

<?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.xsd"> <bean id="HelloWorldHelprt" class="com.main.autowrite.DI.HelloWorldHelper"> <property name="helloWorldImpl" ref="helloWorldImpl" /> </bean> <bean id="helloWorldImpl" class="com.main.autowrite.DI.HelloWorldImpl"/></beans>

HelloWorld.java

package com.main.autowrite.DI;public interface HelloWorld { public void sayHello();}

HelloWorldImpl.java

package com.main.autowrite.DI;public class HelloWorldImpl implements HelloWorld{ public void sayHello() { System.out.println("Hello world"); }}

HelloWorldHelper.java

package com.main.autowrite.DI;public class HelloWorldHelper { private HelloWorldImpl helloWorldImpl; public HelloWorldHelper(){ } public void setHelloWorldImpl(HelloWorldImpl helloWorldImpl){ this.helloWorldImpl = helloWorldImpl; } public void sayHello(){ helloWorldImpl.sayHello(); }}

測試方法:

@Test public void test(){ applicationContext context = new ClassPathXmlApplicationContext("com/main/autowrite/DI/bean.xml"); HelloWorldHelper helper = (HelloWorldHelper)context.getBean("HelloWorldHelprt"); helper.sayHello(); }

例子2:構造器方法依賴注入

在例子1的基礎上

修改HelloWorldHelper類如下:

package com.main.autowrite.DI;public class HelloWorldHelper { private HelloWorldImpl helloWorldImpl; public HelloWorldHelper(HelloWorldImpl helloWorldImpl){ this.helloWorldImpl = helloWorldImpl; } public void sayHello(){ helloWorldImpl.sayHello(); }}

bean.xml

<?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.xsd"> <bean id="HelloWorldHelprt" class="com.main.autowrite.DI.HelloWorldHelper"> <constructor-arg> <ref bean="helloWorldImpl" /> </constructor-arg> </bean> <bean id="helloWorldImpl" class="com.main.autowrite.DI.HelloWorldImpl"/></beans>

測試方法和例子1的一致,無需更改

兩個例子的運行結果均是下圖的結果: 這里寫圖片描述

如需了解靜態工廠以及實例工廠的依賴注入,請點擊這里學習


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 特克斯县| 延边| 县级市| 前郭尔| 屯门区| 清远市| 金溪县| 灵寿县| 和平县| 化隆| 安福县| 兴化市| 景德镇市| 思南县| 宝应县| 铜鼓县| 扎赉特旗| 龙海市| 宿迁市| 石棉县| 浏阳市| 江孜县| 永清县| 蓬安县| 福建省| 周至县| 哈尔滨市| 金川县| 儋州市| 宜兰县| 乌审旗| 福州市| 绥芬河市| 同江市| 黄石市| 清新县| 陕西省| 广饶县| 静乐县| 安新县| 青州市|