第一個Spring程序(DI的實現)


一,依賴注入:Dependency Injection(DI)與控制反轉(IoC),不同角度但是同一個概念。首先我們理解一點在傳統方式中我們使用new的方式來創建一個對象,這會造成對象與被實例化的對象之間的耦合性增加以致不利於維護代碼,這是很難受的。在spring框架中對象實例改由spring框架創建,spring容器負責控制程序之間的關系,這就是spring的控制反轉。在spring容器的角度看來,spring容器負責將被依賴對象賦值給成員變量,這相當於為實例對象注入了它所依賴的實例,這是spring的依賴注入。

二,依賴注入的實現(測試):

①建立Phone接口(call()方法),Student接口(learn()方法) 

1 package com.home.homework;
2 public interface Phone 
3 {
4     //define一個方法
5     public void call();  
6 }
1 package com.home.homework;
2 public interface Student 
3 {
4     //define一個learn()方法
5     public void learn();
6 }

②建立PhoneImpl實現類(實現call()方法),StudentImpl實現類(創建name,phone屬性並實現learn()方法)

1 package com.home.homework;
2 public class PhoneImpl implements Phone{
3     //實現Phone接口中的call()方法
4     public void call()
5     {
6         System.out.println("calling .....! ");
7     }
8 }
 1 package com.home.homework;
 2 public class StudentImpl implements Student
 3 {
 4     //define student's name屬性
 5     private String name="Texsin";
 6     //define一個phone屬性
 7     private Phone phone;
 8     //創建setPhone方法,通過該方法可以為phone賦值
 9     public void setPhone(Phone phone) 
10     {
11         this.phone = phone;
12     }
13     //實現call方法,並且實現Student接口中的learn()方法
14     public void learn()
15     {
16         this.phone.call();
17         System.out.println(name+"is learning via MIX");
18     }
19 }

③建立Spring配置文件beans.xml

④在配置文件中將phone(bean)使用setter方法注入到student(bean)中

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xsi:schemaLocation="http://www.springframework.org/schema/beans
 5         http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
 6     <bean id="phone" class="com.home.homework.PhoneImpl" />
 7     <bean id="student" class="com.home.homework.StudentImpl">
 8         <property name="phone" ref="phone"></property> 
 9     </bean>
10 </beans>

⑤建立TestSpring測試類,在main()方法中進行測試

 1 package com.home.homework;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 public class TestSpring {
 7     public static void main(String[] args)
 8     {
 9         //創建ApplicationContext接口實例,指定XML配置文件,初始化實例
10         ApplicationContext applicationContext=new ClassPathXmlApplicationContext("com/home/homework/beans.xml");
11         //通過容器獲取student實例
12         Student student=(Student) applicationContext.getBean("student");
13         //調用實例中的learn方法
14         student.learn();
15     }
16 }

⑥測試結果

三,測試過程中遇到的錯誤:接口與方法類通過繼承實現不然將報以下錯誤(接口與實現類間通過implements傳遞)

    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM