第一个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传递)


原文链接:https://www.cnblogs.com/texsin/p/10575070.html