依赖注入的方式和注入的配置实例
来源:互联网 发布:淘宝装修免费一键安装 编辑:程序博客网 时间:2024/05/22 13:34
Spring容器是一个IOC容器,通过反转拿到对象然后使用依赖注入到目标组件,下面使用依赖注入,把daobean注入到servicebean的来年各种方式:
首先看一下基本类型对象的注入:
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和服务层进行解耦,后面会介绍更加简单的注解方式注入。
0 0
- 依赖注入的方式和注入的配置实例
- 2.bean的命名和实例化、依赖注入方式
- 依赖注入的方式
- 依赖注入的方式
- 依赖注入的方式
- Spring依赖注入的方式
- spring-依赖注入的方式
- spring依赖注入的方式
- 注入依赖对象的方式
- spring依赖注入的方式
- 10006---依赖注入的方式
- AngularJS的依赖注入方式
- AngularJS的依赖注入方式
- Spring的依赖注入方式
- spring的依赖注入方式
- Spring的依赖注入方式
- Spring的四种依赖注入方式实例
- Spring笔记之一:依赖注入的方式属性注入和构造函数注入
- 扫描神器nmap最佳实践使用
- 嵌套if以及多路if-else语句
- UVa 705 - Slash Maze
- java反编译工具的使用
- 取消交互
- 依赖注入的方式和注入的配置实例
- maven+proguard第三方jar打包混淆
- 小记录
- python爬虫
- Laravel5.x启动过程分析
- Linux下Socket编程函数格式详解
- Android--LayoutInflater解析
- Hibernate 性能优化
- Java的Spi机制心得