一、依赖注入(DI)
依赖注入听起来很高深的样子,其实白话就是:给属性赋值。一共有两种方法,第一是以构造器参数的形式,另外一种就是以setting方法的形式。
1 构造器注入
1 使用构造器注入
使用xml的注入方式
A. 通过参数的顺序
<constructor-arg index="0"><value>张三</value></constructor-arg>
<constructor-arg index="1"><value>56</value></constructor-arg>
B. 通过参数的类型
<constructor-arg type="java.lang.Integer"><value>56</value></constructor-arg>
<constructor-arg type="java.lang.String"><value>张三</value></constructor-arg>
具体实例
假如现在要对一个Person类注入参数,Student是一个另外一个类。
public class Person { private String pid; private String name; private Student student; public Person(String pid, Student student){ this.pid= pid; this.student = student; } public Person(String pid, String name){ this.pid = pid; this.name = name; }}配置applicationContext.xml,假如不进行参数配置,则报错,找不到相应的构造器。配置了相应的参数,则应在类中声明相应的构造函数。
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://.itheima10.spring.iocdi.document.DocumentManager"> <!-- document为一个接口 --> <property name="document"> <!-- wordDocument是一个实现类,赋值给了document接口 --> <ref bean="pdfDocument"/> </property> </bean>使用spring只需要在applicationContext中配置相应的<ref bean="">对象,而不需要关注具体的实现类,实现完全的面向接口编程,这也是为什么spring能够和这么多工具集成的原因。
2.6 mvc实例–模拟structs2
需求描述
建立工程目录
编码:
1、创建Dao层
建立PersonDao接口和实现类PersonDaoImpl
2、建立service层,PersonService接口与PersonServiceImpl实现类
public interface PersonService { public void savePerson();}public class PersonServiceImpl implements PersonService{ private PersonDao personDao; public void setPersonDao(PersonDao personDao) { this.personDao = personDao; } @Override public void savePerson() { this.personDao.savePerson(); }}3、建立Action,PersonAction类
public class PersonAction { private PersonService personService; public void setPersonService(PersonService personService) { this.personService = personService; } public void savePerson(){ this.personService.savePerson(); }}4、配置applicationContext.xml
<!-- 把service,dao,action层的类放入到spring容器中 --> <bean id="personDao" class="xgp.spring.demo.PersonDaoImpl"></bean> <bean id="personService" class="xgp.spring.demo.PersonServiceImpl"> <property name="personDao"> <ref bean="personDao"/> </property> </bean> <bean id="personAction" class="xgp.spring.demo.PersonAction"> <property name="personService"> <ref bean="personService"/> </property> </bean>5、编写测试类testMVC
public class MVCTest { @Test public void testMVC(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); PersonAction personAction = (PersonAction)context.getBean("personAction"); personAction.savePerson();//save person }}上述实例很清楚的展现出了spring的面向接口编程,service层只需调用dao层的接口,而不需要关注于dao层的实现类,action也只需调用service的接口,而不需要关注service的实现类。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。