三、使用SpringIOC进行设值注入

一、本课目标

  • 掌握Spring设值注入

二、Hello,Spring!

需求分析:如何使用Spring实现控制反转?

  • 编写HelloSpring类,输出“Hello,Spring!”
  • 字符串“Spring”通过Spring注入到HelloSpring类中
    步骤:
    1、添加Spring到项目中
    2、编写配置文件
    3、编写代码获取HelloSpring实例

2.1添加Spring到项目中

1、引进jar包:(所有的Spring的内容都可以从Spring官网上下载:repo.spring.io)访问官网——搜索(spring-framework-3.2.13)——我们需要的是:
火狐截图_2018-08-28T02-13-01.855Z.png

解压之后有三个文件夹:
image.png

第一个文件夹是spring的一些api和一些相关内容的介绍,第二个文件夹是它的所有的jar包,第三个文件夹是它的配置文件的元素所以来的schema元素。

项目需要引进的所有的jar包都已经归类整理在E盘。到时候后直接用就好。
2、编写HelloSpring类
代码如下:

package cn.springdemo;

public class HelloSpring {

    // 定义变量who,它的值通过spring框架注入
    private String who;

    /**
     * 定义打印方法,输出一句完整的问候
     */
    public void print() {
        System.out.println("Hello," + this.getWho() + "!");
    }
    
    public String getWho() {
        return who;
    }

    public void setmmp(String who) {
        this.who = who;
    }
     
}

3、编写配置文件
配置文件的头信息去哪里找?
在解压下载下来的spring包中——docs——spring-framework-reference——htmlsingle——用谷歌打开index.html——使用ctrl+f查找“spring-beans”,复制找到的xml文件的头信息即可。
beans标签里面可以写bean标签,bean标签其实就是管理我们的类的标签,里面有两个属性:id和class。class属性是指我们的这个bean要管理的类的完全限定名,id是这个类的别名,其实就相当于new了一个对象出来。bean其实就是为了生成一个对象实例。



    
    
        
        
        
            
            mmp
        
    

4、单元测试
测试类代码:

package test;

import static org.junit.Assert.*;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.springdemo.HelloSpring;

public class HelloSpringTest {

    @Test
    public void test() {
        // 读取配置文件
        ApplicationContext context = 
            new ClassPathXmlApplicationContext("ApplicationContext.xml");
        HelloSpring helloSpring = (HelloSpring) context.getBean("helloSpring");
        helloSpring.print();
    }

}

运行结果:


image.png

注:
1、读取配置文件还可以用ApplicationContext 的下面这个实现类:FileSystemXmlApplicationContext
2、除了使用ApplicationContext 及其实现类之外,还可以用BeanFactory接口及其实现类来对Bean进行管理。

三、小结

image.png

你可能感兴趣的:(三、使用SpringIOC进行设值注入)