首页 > 学院 > 开发设计 > 正文

Spring学习(一)加强 DI依赖注入的小案例

2019-11-06 08:44:51
字体:
来源:转载
供稿:网友

依赖注入,就是一个类依靠另一个类实现, 举个例子,比如说,创建一个A类。在创建一个B类,当然创建过程,SPRing已经帮我们完成了,这时候在A类中建一个B类的私有成员变量set出来,在xml文件中 配置属性标签,在另外的测试类C中通过bean的工厂就能获取到B类中的方法,但是这里注意了,在测试C类中,并没有通过xml文件获取B类的实例。这就是依赖注入,有点绕口,就是B依赖A注入到C的调用中。(可能解释的不是很精准)

接下来,我们把代码贴出来,供大家参考: B类也就是我要创建的Student类:

package com.fly.spring;public class Student { private String sex; public void getSex() { System.out.println("******hello Word*******" + sex); } public void setSex(String sex) { this.sex = sex; }}

A类,我创建的Person类:

package com.fly.spring;public class Person { private String name; public void getName() { student.getSex(); System.out.println("hello" + name); } public void setName(String name) { this.name = name; }// *******Student依赖Person注入的写法****************************************************************** private Student student; public void setStudent(Student student) { this.student = student; }}

再来看看配置文件:

<?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"> <!-- 模拟spring执行过程 创建Person实例:Person person = new Person() IoC <bean> 创建dao实例:Student student = new Student() IoC 将dao设置给person:person.setStudent(student); DI <property> <property> 用于进行属性注入 name: bean的属性名,通过setter方法获得 setStudent ##> Student ##> student ref :另一个bean的id值的引用 --> <!-- 创建Person实例 --> <bean id="person" class="com.fly.spring.Person"> <property name="student" ref="studentID"></property> </bean> <!-- 创建Student实例 --> <bean id="studentID" class="com.fly.spring.Student"></bean> </beans>

接下来就是测试C类了:

package com.fly.spring;import org.junit.Test;import org.springframework.beans.factory.BeanFactory;import org.springframework.beans.factory.xml.XmlBeanFactory;import org.springframework.context.applicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.core.io.ClassPathResource;/** * 演示Spring的依赖注入 * @author Administrator * */public class DiSpring { @Test // IOC public void demo(){ String xmlPath = "com/fly/spring/applicationContext.xml"; ApplicationContext context = new ClassPathXmlApplicationContext(xmlPath); Person person = (Person) context.getBean("person"); person.getName(); } @Test // DI public void demoDi(){ String xmlPath = "com/fly/spring/applicationContext.xml"; BeanFactory factory = new XmlBeanFactory(new ClassPathResource(xmlPath)); Person bean = (Person) factory.getBean("person"); bean.getName(); }}

这片就简单讲解到这里。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表