Spring4框架学习---认识Spring

Spring是什么?

  • Spring是一个开源框架,为了简化java企业级开发而生.使用Spring框架可以使java程序开发变得更加的简单.
  • Spring是一个ICO和AOP(面向切面程序)容器框架.
  • Spring还具有整合其他框架的功能

在这里插入图片描述

  • Spring 模块

在这里插入图片描述

Eclipse的Spring插件

  • 如果使用的是Eclipse工具开发,那么可以安装Spring插件:SPRING TOOL SUITE

在这里插入图片描述

在这里插入图片描述

Spring项目基础环境

  • 编写Spring项目基础所需的jar包

在这里插入图片描述

  • Spring项目还需要有一个配置文件:spring.config.xml(如果使用的是IDEA工具创建的spring项目,该文件会自动生成)

使用IDEA创建Spring项目

  1. 选择创建一个新的项目或者一个新的模块
    • 这里以创建一个新的模块(module)为例
    • 选择Spring项目,IDEA支持自动下载spring4.3和和spring3.2版本的jar包

在这里插入图片描述

  1. 选择模块名称

在这里插入图片描述

  1. IDEA自动下载所需文件中

在这里插入图片描述

  1. 完成之后选择apply应用

在这里插入图片描述

  • 如果IDEA没有创建spring-config.xml文件,可以收工来创建,选择项目右键—>[new]—>[xml Configuration File]—>[spring Config]

在这里插入图片描述

  • 得到的项目结构

在这里插入图片描述

Spring版HelloWorld

  1. 创建一个HelloWorld程序类
package mao.shu.spring;

public class HelloWorld {
    private String userName;

    public void setUserName(String userName) {
        this.userName = userName;
    }
    public void hello(){
        System.out.println("Hello World = userName"+userName);
    }
}


  1. 配置spring-config.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<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">
    
    <!--配置java程序类-->
    <bean id="helloworld" class="mao.shu.spring.HelloWorld">
        <!--类中的属性
        value值必须为"Spring-->
        <property name="userName" value="Xiemaoshu"/>
    </bean>
</beans>
  • 使用Spring实例化Bean对象,并调用hello()方法,大致分为三个步骤
    1. 创建SpringICO容器
    2. 从容器中 获取bean对象
    3. 调用hello()方法
package mao.shu.mian;

import mao.shu.spring.HelloWorld;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Begin {
    public static void main(String[]args){
        ApplicationContext app = 
                new ClassPathXmlApplicationContext("spring-config.xml");
        //getBean()方法参数为配置文件中\<bean\>标签的id值
        HelloWorld helloWorld = (HelloWorld) app.getBean("helloworld");
        helloWorld.hello();
    }
}

  • 最好将spring-config.xml文件放置到path路径下(src)
  • 运行结果
    • 从输出中可以发现,spring自动将对象中的"userName"属性值了

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43386754/article/details/88046163
今日推荐