Spring 学习记录 2 Spring的依赖注入
2014-10-22 12:27
375 查看
上篇,我们用一个例子分析了依赖注入的作用。
这篇,将介绍最简单的 Spring 依赖注入。
用 Spring 时,你可能会很头大。
版本这么多,用哪个版本?
模块这么多,哪个是负责哪块?
这个我也不太清楚。
我使用 maven 管理依赖。
Spring 中用容器来管理(创建和销毁)bean。
常用的容器是 org.springframework.context.ApplicationContext,它是个接口。
常用的实现有 org.springframework.context.support.ClassPathXmlApplicationContext。
建一个叫 ivo 的包,里面创建 Weapon 接口,BowAndArrow 类,Person 类,实现一如上篇。
Spring 的容器需要一个配置文件,来让它明白,该管理哪些 bean。
为了说明这个配置文件的命名是无所谓的,就命名 noname.xml 吧。
这里就是把依赖注入,由代码形式改为了 xml 形式,有好处吗?
有个毛好处,一个类还得两处声明,但这就是 Spring 的规则。
使用到是更方便了,毕竟把一部分逻辑写到 xml 了。。。
Spring 配置的 bean 默认都是单例。
这篇,将介绍最简单的 Spring 依赖注入。
用 Spring 时,你可能会很头大。
版本这么多,用哪个版本?
模块这么多,哪个是负责哪块?
这个我也不太清楚。
我使用 maven 管理依赖。
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.4.RELEASE</version> </dependency> </dependencies>
Spring 中用容器来管理(创建和销毁)bean。
常用的容器是 org.springframework.context.ApplicationContext,它是个接口。
常用的实现有 org.springframework.context.support.ClassPathXmlApplicationContext。
建一个叫 ivo 的包,里面创建 Weapon 接口,BowAndArrow 类,Person 类,实现一如上篇。
Spring 的容器需要一个配置文件,来让它明白,该管理哪些 bean。
为了说明这个配置文件的命名是无所谓的,就命名 noname.xml 吧。
<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"> <bean id="weapon" class="ivo.BowAndArrow"/> <bean id="person" class="ivo.Person"> <constructor-arg ref="weapon"/> </bean> </beans>
这里就是把依赖注入,由代码形式改为了 xml 形式,有好处吗?
有个毛好处,一个类还得两处声明,但这就是 Spring 的规则。
使用到是更方便了,毕竟把一部分逻辑写到 xml 了。。。
public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("noname.xml"); Person person = (Person)applicationContext.getBean("person"); person.killEnemy(); }
Spring 配置的 bean 默认都是单例。
相关文章推荐
- [导入]学习spring依赖注入--备忘
- Spring学习——依赖注入
- Spring 学习总结(一)依赖注入的理解
- Spring学习(一)——Spring中的依赖注入简介【转】
- Spring.Net 入门学习(一)实现控制器翻转与依赖注入
- 传智播客 Spring学习 xml配置依赖注入
- Spring 学习总结(一)依赖注入的理解
- Spring学习笔记(二)依赖注入Dependency Injection
- 框架学习之Spring 第二节 采用Spring管理Bean和依赖注入
- Spring架构学习(2)通过Properties文件实现依赖注入
- Spring视频学习(一)依赖注入原理
- 框架学习之Spring 第二节 采用Spring管理Bean和依赖注入
- Spring学习总结1(基础与IOC依赖注入)
- 框架学习之Spring 第二节 采用Spring管理Bean和依赖注入
- ITCAST视频-Spring学习笔记(编码剖析Spring依赖注入的原理)
- spring2.5 基于注解依赖注入学习--01
- Spring依赖注入原理学习
- Spring2.5学习笔记1-控制反转-依赖注入类型
- SPRING.NET 1.3.2 学习5--依赖注入
- spring学习笔记3--依赖注入对象