Spring控制反转案例快速入门

1.下载Spring最新开发包 

    http://www.springsource.org/download/community 下载spring3.2 的开发包

目录结构(spring-framework-3.2.0.RELEASE)

* docs 存放API和 规范文档

* libs 开发jar

* schemas 开发过程中需要导入xmlschema 约束

我们还有一个依赖包(spring-framework-3.0.2.RELEASE-dependencies),里面有开发涉及的所有jar包,以后开发可以从这里面找jar包。


2.复制Spring开发 jar包到工程

    复制核心容器包含jar包 (beanscorecontextexpression language

    spring 的 jar包 需要依赖 commons-logging的 jar commons-logging 类似 slf4j 是通用日志组件,需要整合 log4j ),拷贝log4j.properties

扫描二维码关注公众号,回复: 998170 查看本文章

提示:spring3.0.X 版本 asm jar包 已经被合并到 spring core包中


3.理解IoC控制反转和DI依赖注入

IoC Inverse of Control 反转控制的概念,就是将原本在程序中手动创建UserService对象的控制权,交由Spring框架管理,简单说,就是创建UserService对象控制权被反转到了Spring框架

DIDependency Injection 依赖注入,在Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件


面试题: IoC 和 DI的区别? 

IoC 控制反转,指将对象的创建权,反转到Spring容器 , DI 依赖注入,指Spring创建对象的过程中,将对象依赖属性通过配置进行注入 

4.编写Spring核心配置文件

src目录创建 applicationContext.xml 

    在docs\spring-framework-reference\html 找到 xsd-config.html,在最下方引入bean的约束

 
   
  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="
  4. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
编写配置文件applicationContext.xml
 
    
  1. <!-- 配置使用哪个实现类 对 IHelloService 进行实例化-->
  2. <!-- 配置实现类HelloServiceImpl,定义名称helloService-->
  3. <bean id="helloService" class="cn.itcast.spring.a_quickstart.HelloServiceImpl">
  4.         <!-- helloService 依赖 info属性 --> <!-- 通过property配置spring创建 helloService对象时,自动调用 setInfo方法 完成属性注入 --> <property name="info" value="传智播客"></property>
  5. </bean>
 

5.在程序中读取Spring配置文件,通过Spring框架获得Bean,完成相应操作

    加载classpathsrc): new ClassPathXmlApplicationContext("applicationContext.xml");

    加载磁盘路径:new FileSystemXmlApplicationContext("applicationContext.xml");

 
   
  1. public static void main(String[] args) {
  2.     // 传统写法 (紧密耦合)
  3. HelloServiceImpl helloService = new HelloServiceImpl();
  4.     // 手动调用 set 方法为 info 进行赋值 helloService.setInfo("spring");
  5. helloService.sayHello();
  6. // 工厂+反射 +配置文件 ,实例化 IHelloService的对象
  7. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  8. // 通过工厂根据配置名称获得实例对象
  9. IHelloService iHelloService2 = (IHelloService) applicationContext.getBean("helloService");
  10. iHelloService2.sayHello();
  11. // 控制反转,对象的创建权被反转到 Spring框架
  12. }

说明:
     IHelloService接口定义:
 
    
  1. // 接口
  2. public interface IHelloService {
  3. public void sayHello();
  4. }
    HelloServiceImpl实现类定义:
 
    
  1. // 实现类
  2. public class HelloServiceImpl implements IHelloService {
  3.     private String info;
  4. public void sayHello() {
  5. System.out.println("hello,"+info);
  6. }
  7.     // HelloServiceImpl 的实例 依赖 String 类型 info 数据 // UML OOD设计中 依赖强调 方法中参数 public void setInfo(String info) { this.info = info; }
  8. }

猜你喜欢

转载自blog.csdn.net/a_blackmoon/article/details/80194213
今日推荐