依赖注入的方式和注入的配置实例
2016-03-24 14:49
330 查看
Spring容器是一个IOC容器,通过反转拿到对象然后使用依赖注入到目标组件,下面使用依赖注入,把daobean注入到servicebean的来年各种方式:
首先看一下基本类型对象的注入:
1.使用构造器注入
2.使用setter方法注入
注入XML配置:
1.配置属性注入其他bean
2.使用内部bean注入其他bean
无论是采用何种方式注入属性,何种方式注入其他的bean 都是为了业务bean和服务层进行解耦,后面会介绍更加简单的注解方式注入。
首先看一下基本类型对象的注入:
1.使用构造器注入
public class PersonServiceBean implements PersonService{ private PersonDao personDao; // 接口 public PersonServiceBean(PersonDao personDao) { this.personDao = personDao; } public void save() { personDao.add(); } }
2.使用setter方法注入
public class PersonServiceBean implements PersonService{ private PersonDao personDao; public void setPersonDaoBean(PersonDao personDao) { this.personDao = personDao; } public void save() { personDao.add();// 接口的add方法,不关心谁实现了这个接口 } }
注入XML配置:
1.配置属性注入其他bean
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <bean id="personDao" class="com.heying.dao.impl.PersonDaoBean"></bean> <bean id="personService" class="com.heying.service.PersonServiceBean"> <property name="personDao" ref="personDao"></property> <!-- 注入的属性,注入值(注入的名称,spring会按照这个名称在容器里面寻找相应的bean,[已经配置在上面]) --> </bean> </beans>
2.使用内部bean注入其他bean
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <!-- <bean id="personDao" class="com.heying.dao.impl.PersonDaoBean"></bean> --> <bean id="personService" class="com.heying.service.PersonServiceBean"> <property name="personDao"> <bean class="com.heying.dao.impl.PersonDaoBean"></bean> </property> </bean> </beans>
无论是采用何种方式注入属性,何种方式注入其他的bean 都是为了业务bean和服务层进行解耦,后面会介绍更加简单的注解方式注入。
相关文章推荐
- JavaScript中的依赖注入详解
- 浅析依赖注入框架Autofac的使用
- 浅析Node.js中使用依赖注入的相关问题及解决方法
- 如何用js 实现依赖注入的思想,后端框架思想搬到前端来
- Javascript技术栈中的四种依赖注入详解
- 深入理解Javascript里的依赖注入
- Javascript技术栈中的四种依赖注入小结
- 详解Angularjs中的依赖注入
- AngularJs动态加载模块和依赖注入详解
- Spring的@Autowired实践感知
- Android学习之 使用依赖注入函数库Roboguice
- 控制反转与依赖注入
- Java反射及依赖注入简单模拟
- Spring3核心技术之DI依赖注入
- IoC
- spring学习笔记3——注入依赖对象
- Spring学习1--前传
- Autofac官方文档翻译——(二)组件注册(未完)
- Spring的IoC/DI的理解
- spring的依赖注入