当前位置: 首页 > news >正文

初识 Spring 框架

文章目录

    • 一、Spring 介绍
    • 二、Spring 下载安装
    • 三、编写入门程序
      • 1.项目文件构架
      • 2.引入相关依赖
      • 3.创建实体类
      • 4.Spring 配置文件
      • 5.编写测试类
    • 四、控制反转与依赖注入
      • 1.控制反转概念
      • 2.依赖注入概念
      • 3.依赖注入的类型
      • 4.依赖注入的应用

一、Spring 介绍

Spring 是由 Rod Johnson 组织和开发的一个分层的 Java SE/EE 一站式轻量级开源框架。它最为核心的理念是 loC(控制反转)和 AOP(面向切面编程),其中,loC 是 Spring 的基础,它支撑着 Spring 对 JavaBean 的管理功能,AOP 是 Spring 的重要特性,AOP 是通过预编译方式和运行期间动态代理实现程序功能,也就是说可以在不修改源代码的情况下,给程序统一添加功能。

Spring 在表现层、业务逻辑层和持久层的作用:
① 在表现层它提供了 Spring MVC 框架,并且 Spring 还可以与 Struts 框架整合;
② 在业务逻辑层可以管理事务、记录日志等;
③ 在持久层可以整合 MyBatis、Hibernate、JdbcTemplate 等技术。

Spring 框架的优点:

(1)Spring 是一种非侵入式框架,所谓非侵入式是指 Spring 框架的 API 不会再业务逻辑上出现,也就是说业务逻辑应该是纯净的,不能出现与业务逻辑无关的代码。由于业务逻辑中没有 Spring 的 API,所以业务逻辑代码也可以从 Spring 框架快速地移植到其他框架;
(2)Spring 就是一个大工厂,可以将所有对象的创建和依赖关系的维护工作都交给 Spring 容器管理,大大降低了组件之间的耦合性;
(3)Spring 提供了对 AOP 的支持,AOP 可以将一些通用的任务进行集中处理,如安全、事务和日志等,以减少通过传统 OOP 方法带来的代码冗余和繁杂;
(4)在 Spring 中,可以直接通过 Spring 配置文件管理数据库事务,省去了手动编程的繁琐,提高了开发效率;
(5)Spring 提供了对 Junit 的支持,开发人员可以通过 Junit 进行单元测试;
(6)Spring 提供了一个广阔的基础平台,其内部提供了对各种框架的直接支持,如 Struts、Hibernate、MyBatis、Ouartz 等,这些优秀框架可以与 Spring 无缝集成;
(7)Spring 对 Java EE 开发中的一些 API(如 JDBC、JavaMail 等)都进行了封装,大大降低了这些 API 的使用难度。

二、Spring 下载安装

(1)Spring 官网地址https://spring.io/

(2)Projects → Spring Framework

在这里插入图片描述

(3)打开 github

在这里插入图片描述

(4)往下翻,找到 Access to Binaries,点击下面的网址

在这里插入图片描述

(5)打开后继续往下滑,选择 Downloading a Distribution 下的网址

在这里插入图片描述

(6)点击 Artifacts,依次展开 release → org → springframework → spring

在这里插入图片描述

在这里插入图片描述

(7)选择最新版本,点击右侧链接

在这里插入图片描述

(8)点击第一个开始下载

在这里插入图片描述

在使用 Spring 开发时,除了要使用自带的 jar 包外,Spring 的核心容器还需要依赖 commons.logging 的 jar 包,但是由于我们创建的是 Maven 工程,这些架包 Maven 都可以帮我们自动完成,所以我们只需了解即可。

三、编写入门程序

1.项目文件构架

在这里插入图片描述

2.引入相关依赖

 <dependencies>
        <!-- spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.3.9</version>
        </dependency>

        <!-- spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.9</version>
        </dependency>

        <!-- spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.3.9</version>
        </dependency>

        <!-- spring-expression -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>5.3.9</version>
        </dependency>

        <!-- commons-logging -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- jupiter -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.9</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

在这里插入图片描述

3.创建实体类

在 src/main/java/com.tyut 下创建实体类,HelloSpring.java。

//HelloSpring.java
package com.tyut;

public class HelloSpring {
    private String userName;
    private void setUserName(String userName) {
        this.userName = userName;
    }
    public void show() {
        System.out.println(userName+"你好,Spring");
    }
}

4.Spring 配置文件

找到我们之前下载好的 Spring 文件夹,docs → reference → html → index.html → Core → 往下滑找到 Configuration Metadata,再往下滑一点可以看到一段代码,这就是我们所要的配置文件模板,直接复制。

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

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="..." class="...">  
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>

为了后续开发方便,我们不妨把它做成一个模板,以后直接使用就可以了。

模板具体步骤,File → Settings → Editor → File and Code Templates → 加号 → 填写名称和文件类型,然后把配置代码复制进去即可 → Apply

在这里插入图片描述

有了模板之后,我们的选项卡中就可以看到 applicationContext,在 resources 目录下创建配置文件,我这里名字依然叫 applicationContext!

在这里插入图片描述

5.编写测试类

//MyTest.java
package com.tyut;

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

public class MyTest {
    public static void main(String[] args) {
        //1.获取spring容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2.从spring容器获取对象
        HelloSpring helloSpring = (HelloSpring)ac.getBean("helloSpring");
        //3.调用对象的方法
        helloSpring.show();
    }
}

在这里插入图片描述

四、控制反转与依赖注入

1.控制反转概念

控制反转(Ioc)是面向对象编程中的一个设计原则,用来降低程序代码之间的耦合度。
在传统面向对象编程中,获取对象的方式是用 new 关键字主动创建一个对象,也就是说应用程序掌握着对象的控制权。
Ioc 控制反转机制指的是对象由 Ioc 容器统一管理,当程序需要使用对象时,可以直接从 Ioc 容器中获取,这样对象的控制权就从应用程序转移到了 Ioc 容器。借助 Ioc 容器实现具有依赖关系对象之间的解耦,各个对象类封装之后,通过 Ioc 容器来关联这些对象类。

2.依赖注入概念

依赖注入(DI),就是由 Ioc 容器在运行期间动态地将某种依赖资源注入对象之中,例如,将对象 B 赋值给对象 A 的成员变量。依赖注入的基本思想是,明确地定义组件接口,独立开发各个组件,然后根据组件的依赖关系组装运行。

依赖注入和控制反转的比较:
依赖注入和控制反转是从不同角度来描述了同一件事情。依赖注入是从应用程序的角度描述,即应用程序依赖 Ioc 容器创建并注入它所需要的外部资源;而控制反转是从 Ioc 容器的角度描述,即 Ioc 容器控制应用程序,由 Ioc 容器反向地向应用程序注入应用程序所需要的外部资源,这里的外部资源可以是外部实例对象,也可以是外部文件对象等。

3.依赖注入的类型

依赖注入的作用就是在使用 Spring 框架创建对象时,动态的将其所依赖的对象注入到 Bean 组件中,依赖注入通常有两种实现方式,一种是构造方法注入,另一种是属性 setter 方法注入。这两种实现方式具体介绍如下:

① 构造方法注入

构造方法注入是指 Spring 容器调用构造方法注入被依赖的实例,构造方法可以是有参的或者是无参的。Spring 在读取配置信息后,会通过反射方式调用实例的构造方法,如果是有参构造方法,可以在构造方法中传入所需的参数值,最后创建类对象。

//User1.java
package com.tyut;

public class User1 {
    private int id;
    private String username;
    private String password;
    public User1(Integer id,String username,String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    @Override
    public String toString() {
        return "User1{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

<!-- applicationContext.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="user1" class="com.tyut.User1">
        <constructor-arg name="id" value="1"></constructor-arg>
        <constructor-arg name="username" value="张三"></constructor-arg>
        <constructor-arg name="password" value="123"></constructor-arg>
    </bean>
</beans>
//MyTest.java
package com.tyut;

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

public class MyTest {
    public static void main(String[] args) {

        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        User1 user1 = (User1) ac.getBean("user1");
        System.out.println(user1);
    }
}

在这里插入图片描述

一个 constructor-arg 元素表示构造方法的一个参数,且定义时不区分顺序,只需要通过 constructor-arg 元素的 name 属性指定参数即可。constructor-arg 元素还提供了 type 属性和 index 属性来确定参数,实际开发中,我们推荐使用 name 属性来确定参数。同时还有 value 属性和 ref 属性,value 属性用来给基本类型赋值,ref 属性用来给引用类型进行赋值。

当使用 type 属性确定参数时,如果两个参数的类型是一样的,那么定义时就要区分顺序了!

② 属性 setter 方法注入

属性 setter 方法注入是 Spring 最主流的注入方法,这种注入方法简单、直观,它是在被注入的类中声明一个 setter 方法,通过 setter 方法的参数注入对应的值。

//User2.java
package com.tyut;

public class User2 {
    private int id;
    private String username;
    private String password;

    public void setId(int id) {
        this.id = id;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User1{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

<bean id="user2" class="com.tyut.User2">
        <property name="id" value="2"></property>
        <property name="username" value="李四"></property>
        <property name="password" value="1234"></property>
    </bean>
package com.tyut;

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

public class MyTest {
    public static void main(String[] args) {

        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        User2 user2 = (User2) ac.getBean("user2");
        System.out.println(user2);
    }
}

在这里插入图片描述

注意配置文件中 name 的值并不是属性名,而是 set 方法去掉 set 关键字后的名字!

4.依赖注入的应用

① 在 com.tyut 包下创建 dao 层包,在该包下创建 UserDao 接口类。

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

② 提供 UserDao 接口的实现类,dao 层下 impl.UserDaoImpl。

在这里插入图片描述

在这里插入图片描述
③ com.tyut下创建 service 包 下的 UserService 接口。

在这里插入图片描述

在这里插入图片描述

④ 提供 UserService 接口的实现类,service 层下 impl.UserServiceImpl。

在这里插入图片描述

如何自动生成 get 方法?
鼠标右键 Generate,Setter,Ctrl+A 全部选中,回车键!

⑤ 再次来到配置文件中,有两个对象需要配置。

<!--applicationContext.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- userDao对象 -->
    <bean id="userDao" class="com.tyut.dao.impl.UserDaoImpl"></bean>
    <!-- userService对象 -->
    <bean id="userService" class="com.tyut.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>
</beans>

⑥ 编写测试类

package com.tyut;

import com.tyut.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {

        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) ac.getBean("userService");
        boolean flag = userService.login("张三","123");
        if (flag) {
            System.out.println("登录成功!");
        } else {
            System.out.println("登录失败!");
        }
    }
}

在这里插入图片描述

相关文章:

  • java计算机毕业设计高校心理测评管理系统源码+mysql数据库+系统+lw文档+部署
  • C++【特殊类的设计】【单例设计模式】
  • 创新赋能合作伙伴,亚马逊云科技re:Invent科技盛宴
  • Ubuntu 安装“安装程序向硬盘复制文件时遇到错误[Errno 5] Input/output error”错误解决过程记录
  • 第五届传智杯-初赛【B组-题解】
  • 我的DW个人网站设计——安徽宣城6页HTML+CSS+JavaScript
  • 【学习笔记】Reids的哨兵机制
  • 傻白入门芯片设计,芯片键合(Die Bonding)(四)
  • Servlet(Cookie和Session)
  • 四轴斜转魔方
  • 详解设计模式:工厂方法模式
  • C++游戏game | 井字棋游戏坤坤版(配资源+视频)【赋源码,双人对战】
  • 综合实验 电子记事本的设计与实现——Java
  • CSS 选择器
  • 进程的调度
  • 程序员注意!35岁前,别靠死工资过日子
  • Ubuntu22.2下C语言编程实现,首次,最佳适应算法
  • SpringBoot: Controller层的优雅实现
  • C语言学习笔记(十)
  • 前端框架Vue语法部分(一)
  • 美乌矿产协议签署被曝“临门一脚”时生变,美方提附加条件
  • 李铁案二审驳回上诉,维持一审有期徒刑20年的判决
  • 媒体:黑话烂梗包围小学生,“有话好好说”很难吗?
  • 上海开花区域结果,这项田径大赛为文旅商体展联动提供新样本
  • 宁波银行一季度净利74.17亿元增5.76%,不良率持平
  • 上海乐高乐园建设进入最后冲刺,开园限量纪念年卡将于5月开售