JavaSpring学习总结(一)

1.安装Spring

视频地址:下载安装Spring,看第3集入门案例
commons-logging日志包下载地址:下载commons-logging
在这里插入图片描述

2.创建一个普通工程

打开IDEA软件,点击新建工程。具体步骤如下:

2.1直接下一步

在这里插入图片描述
## 2.2

2.2 选择项目位置

在这里插入图片描述

2.3 导入下载的JAR包

  1. 先建一个目录(名称就叫lib
    在这里插入图片描述
    在这里插入图片描述
  2. 回到文件夹(下载的jar包下)
    在这里插入图片描述
    3.回到IDEA,右键lib文件夹,选择粘贴
    在这里插入图片描述
    在这里插入图片描述
    4.创建一个Main类(具体操作不再详细介绍,这是属于Java基础内容)
    在这里插入图片描述

3.项目中进行导入jar包

3.1 进入项目结构

在这里插入图片描述

3.2 选择模块

  1. 选中位置(不要选错了!)
    在这里插入图片描述
  2. 添加jar包
    在这里插入图片描述
    然后选择刚才复制粘贴在lib文件夹中的jar包。
    在这里插入图片描述
    在这里插入图片描述

4.建一个普通的类和方法(测试用的)

首先建立一个User类和add()方法
在这里插入图片描述

5.如何通过Spring来创建对象(IOC)

5.1 创建一个配置文件(xml格式)

在这里插入图片描述

5.2 配置文件

在这里插入图片描述

5.3 bean标签

属性
属性
bean标签
id
class

i d : \color{red}id: id:填上你要实例化的对象,如:user
c l a s s : \color{red}class: class:填上实例化对象(id的值)的包名+类名,如:com.fly.User

    <!--id指的是User这个类,class指的是这个类的地址(包名+类名)-->
    <bean id="user" class="com.fly.User">
		
    </bean>

6.测试自己写的Spring配置文件

返回到Main类,在main()方法中进行测试。
步 骤 如 下 : \color{#2586c0}步骤如下:

  1. 加 载 配 置 文 件 \color{#00ff18}加载配置文件
  2. 从 配 置 文 件 中 获 取 对 象 \color{#ffc500}从配置文件中获取对象
  3. 使 用 该 对 象 , 进 行 对 方 法 的 调 用 \color{#f500ff}使用该对象,进行对方法的调用 使

6.1 加载配置文件

ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

使用该方法来加载配置文件,需要保证该类存在src文件夹下
ClassPathXmlApplicationContext(“bean1.xml”); 其中参数需要的是你要加载的配置文件的名称。
在这里插入图片描述

6.2 从Spring配置文件中获取对象

context.getBean("user",User.class);

该方法返回的类型是一个类。用一个类来接收它。

User user = context.getBean("user",User.class);

getBean方法的参数:
(1)user : 配置文件当中的id值
(2)User.class : 要创建的是User类的实例

6.3 使用该对象

加载完配置文件&获取了对象 ==> 可以正常使用该对象了!

user.add();//在这里同样可以调用User类的方法了

在这里插入图片描述

7.最后,完整代码做个总结

项 目 结 构 \color{#ad0000}项目结构
在这里插入图片描述

M a i n 类 \color{#ad0000}Main类 Main

package com.fly;

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

public class Main {

    public static void main(String[] args) {

        //1.加载配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        //2.从配置文件中获取对象
        User user = context.getBean("user",User.class);
        //3.使用这个对象
        user.add();
    }

}

U s e r 类 \color{#ad0000}User类 User

package com.fly;

public class User {

    //简单的一个输出方法
    public void add(){
        System.out.println("添加...");
    }

}

b e a n 1. x m l 配 置 文 件 \color{#ad0000}bean1.xml配置文件 bean1.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">

    <!--id指的是User这个类,class指的是这个类的地址(包名+类名)-->
    <bean id="user" class="com.fly.User">

    </bean>
</beans>

视频资料:点击这里查看视频,尚硅谷视频

posted @ 2022-03-27 12:53  辰梦starDream  阅读(1)  评论(0编辑  收藏  举报  来源