当前位置: 移动技术网 > IT编程>开发语言>Java > 第一个Spring程序(DI的实现)

第一个Spring程序(DI的实现)

2019年03月22日  | 移动技术网IT编程  | 我要评论

一,依赖注入: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传递)

    

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网