Java Spring

目录

一、spring简介

1.1、什么是Spring

1.2 IOC

1.3、DI

二.创建Spring项目

2.1 创建一个普通的maven项目

2.2  引入maven依赖

三、Spring的创建和使用

3.1  创建Bean

3.2  将Bean放入到容器中 

3.3 获取Bean对象

3.4、创建 Spring 上下文

3.5  获取指定的 Bean 对象  

四、引入注解的方式

4.1 类注解

4.2 方法注解

4.3 传递参数

五、对象装配

5.1 属性注入

1.@Autowired注解

2.@Resource注解

3.Setter方法注入

4.构造函数注入

5.2 三种方法的优缺点

1.属性注入

2.Setter注入(Spring 3.X推荐)

3.构造函数注入(Spring 4.X推荐)

六.Bean的作用域

6.1   六种作用域简介

6.2 singleton

6.3 prototype

6.4  request

6.5  session

6.6  application

7.7  websocket:

七.Spring的启动流程 

八.Bean的生命周期


spring简单的使用方式:使用注解的方法

因为用的是JDK17,需要用spring6.几的版本才行

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>6.1.2</version>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:content="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <content:component-scan base-package="com.zyf"></content:component-scan>
</beans>

Bean注解默认名字,前两个字母都是大写就得是原名,只有首字母大写,会是全小写

一、spring简介

1.1、什么是Spring

Spring 指的是 Spring Framework(Spring 框架)

它可以让 Java 企业级 的应用程序开发起来更简单。

⽤⼀句话概括 Spring:Spring 是包含了众多工具方法的 IOC 容器

1.2 IOC

IoC = Inversion of Control 翻译成中文是控制反转的意思,也就是说 Spring 是⼀个“控制反转”的容器,具体这里指对于依赖对象控制器的反转.

通常一个类

class A{
B b=new B();
}

这个B对象的生命周期是由A类来管理的,现在Spring将B的生命周期交给Spring来统一管理.这样就发生了控制权的反转.

当我们创建一个车的时候,要先创建车身,车身又需要底盘,底盘又依赖于轮胎,这样一层一层的依赖,使代码的耦合度很高

IOC的主要优势就是 程序解耦,耦合度降低

Spring 是一个 IoC(控制反转)容器,重点还在“容器”二字上,那么它就具备两个最基础的功

  • 将对象存入到容器;
  • 从容器中取出对象。

1.3、DI

DI 是 Dependency Injection 的缩写,翻译成中文是“依赖注入”的意思。

如果说IOC是一种思想的话,那么DI就是思想的实现

二.创建Spring项目

2.1 创建一个普通的maven项目

2.2  引入maven依赖

我这里是用的jdk17,所以spring的版本要比较高的才行

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>6.1.2</version>
</dependency>

引入依赖之后,刷新一下maven就能引入了

三、Spring的创建和使用

3.1  创建Bean

Bean就是Java中一个普通的对象

3.2  将Bean放入到容器中 

在创建好的项目中添加 Spring 配置文件 spring-config.xml,将此⽂件放到 resources 的根目录下

Spring 配置⽂件的固定格式为以下内容: 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:content="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
</beans>

接下来我么只需要将student对象注册到spring容器中即可

<bean id ="user" class="com.zyf.User"></bean>

id为唯一标识这个student对象的.class为Student对象的位置 

3.3 获取Bean对象

 获取并使用 Bean 对象,分为以下 3 步:
        1. 得到 Spring 上下文对象,因为对象都交给 Spring 管理了,所以获取对象要从 Spring 中获           取,那么就得先得到 Spring 的上下文。

        2. 通过 Spring 上下文,获取某一个指定的 Bean 对象。
        3. 使用 Bean 对象。     

3.4、创建 Spring 上下文

 public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
    }

除了 ApplicationContext 之外,我们还可以使用 BeanFactory 来作为 Spring 的上下文,如下代码所示:

BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("spirng-config.xml"));

ApplicationContext 和 BeanFactory 效果是一样的,ApplicationContext 属于 BeanFactory 的子类

他们的区别如下

BeanFactory 提供了基础的访问容器的能力,而 ApplicationContext属于 BeanFactory 的子类,它除了继承了 BeanFactory 的所有功能之外,它还拥有独特的特性,还添加了对国际化支持、资源访问支持、以及事件传播等方面的支持。

  • 从性能方面来说:ApplicationContext 是一次性加载并初始化所有的 Bean 对象(预加载),而BeanFactory 是需要那个才去加载那个(懒加载),因此更加轻量。

3.5  获取指定的 Bean 对象  

 public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

        User user = (User)context.getBean("user");
        user.show();
    }

通过在xml文件里定义的bean的id可以获取到相应的对象.

四、引入注解的方式

4.1 类注解

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:content="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <content:component-scan base-package="com.zyf"></content:component-scan>
</beans>

base-package = “com.zyf”,表示的是要扫描的路径是com.zyf下面的类

 五大注解@Controller  @Service @Repository  @Component  @Configuration

每一个注解上面都有@Component,说明这几个注解都是 @Component注解的子类,所以他们实现的功能都是一样的,那为什么还要有这么多不同的注解呢?

让程序员看到类注解之后,就能直接了解当前类的用途,比如:

  • @Controller:表示的是业务逻辑层;
  • @Servie:服务层;
  • @Repository:持久层;
  • @Configuration:配置层。
  • @Compoent:其他层

命名规范:

注解生成bean的id为类的名称的首字母小写.当首字母和第二个字母都为大写字母的时候,直接返回原名字.

@Controller
public class Student {
    private int age;
    private String name;

    public Student(){
    }
    public void show(){
        System.out.println("show()");
    }
}
public class App {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
        Student student = (Student) applicationContext.getBean("student");
        student.show();
    }
}

通过注解,不用一个一个添加Bean到xml当中,让spring帮我们去扫描指定的路径就行

4.2 方法注解

1. 方法注解需要搭配类的五大注解来使用

2. Bean对应的bean名是方法名

3 Bean重命名之后,就只能用自己定义的名字了

4.3 传递参数

1、五大注解的方式:

2、之前配置Bean的形式

五、对象装配

5.1 属性注入

1.@Autowired注解

现在要求将UserService注入到UserController类中

先来创建service类

@Service
public class UserService {

    public User getUser(Integer id) {
        User user = new User();
        user.setAge(id);
        user.setName("zyf-"+id);
        return user;
    }
}

再来创建controller类

@Controller
public class UserController {
    @Autowired
    UserService userService;
    
    public User getUser(Integer id) {
        return userService.getUser(id);
    }
 
}

测试: 

public class App3 {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        UserController userController = (UserController)context.getBean("userController");

        userController.getName(18);
    }
}

2.@Resource注解

在进行类注入时,除了可以使用 @Autowired 关键字之外,我们还可以使⽤ @Resource 进行注入,如下代码所示:

@Controller
public class UserController {
    @Resource
    UserService userService;
 
    public User getUser(Integer id) {
        return userService.getUser(id);
    }
 
}

同时 @Resource注解可以注入指定名字的对象

 @Resource(name = "aaa") / /代表注入name=aaa的对象
 UserService userService;

区别

  • 出身不同:@Autowired 来自于 Spring,而 @Resource 来自于 JDK 的注解;
  •  使用时设置的参数不同:相比于 @Autowired 来说,@Resource 支持更多的参数设置,例如name 设置,根据名称获取 Bean。
  • @Autowired 可用于 Setter 注入、构造函数注入和属性注入,而 @Resource 只能用于 Setter 注入和属性注入,不能用于构造函数注入。
  • 当然@Autowired搭配@qualiier能实现指定

3.Setter方法注入

只是Autowired的位置改变就行了

//Setter 注入
@Controller
public class UserController2 {
    private UserService userService;

    //只是Autowired的位置变化就行了
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void getName(Integer id){
        userService.getUser(id);
    }
}
4.构造函数注入

通过构造函数注入,只有一个构造函数,可以省略@Autowired注解,如果存在多个构造函数,需要在使用的那个构造函数上面加@Autowired注解,否则就会报如下错误

5.2 三种方法的优缺点

1.属性注入

优点:

  1. 简洁,使用方便;

缺点:

  1. 只能用于lOC容器,如果是非IOC容器不可用,并且只有在使用的时候才会出现NPE(空指针异常)。
  2. 不能注入一个final修饰的属性
2.Setter注入(Spring 3.X推荐)

优点:

  1. 方便在类实例之后,重新对该对象进行配置或者注入

缺点:

  1. 不能注入一个final修饰的属性
  2. 注入对象可能会被改变,因为setter方法可能会被多次调用,就有被修改的风险. 
3.构造函数注入(Spring 4.X推荐)

优点:

  1. 可以注入final修饰的属性
  2. 注入的对象不会被修改
  3. 依赖对象在使用前一定会被完全初始化,因为依赖是在类的构造方法中执行的,而构造方法是在类加载阶段就会执行的方法。
  4. 通用性好,构造方法是JDK支持的,所以更换任何框架,他都是适用的。

缺点: 

  1. 注入多个对象时,代码会比较繁琐

六.Bean的作用域

6.1   六种作用域简介

限定程序中变量的可用范围叫做作用域,或者说在源代码中定义变量的某个区域就叫做作用域。 而 Bean 的作用域是指 Bean 在 Spring 整个框架中的某种行为模式,比如 singleton 单例作用域,就 表示 Bean 在整个 Spring 中只有一份,它是全局共享的,那么当其他人修改了这个值之后,那么另一个人读取到的就是被修改的值。

  1. singleton:单例作用域(默认)
  2. prototype:原型作用域(多例作用域)
  3. request:请求作用域
  4. session:会话作用域
  5. application:全局作用域
  6. websocket:HTTP WebSocket 作用域

注意后 4 种状态是 Spring MVC 中的值,在普通的 Spring 项目中只有前两种

6.2 singleton

  • 官方说明:(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
  • 描述:该作用域下的Bean在IoC容器中只存在一个实例:获取Bean(即通过applicationContext.getBean等方法获取)及装配Bean(即通过@Autowired注入)都是同一个对象。
  • 场景:通常无状态的Bean使用该作用域。无状态表示Bean对象的属性状态不需要更新
  • 备注:Spring默认选择该作用域

6.3 prototype

  • 官方说明:Scopes a single bean definition to any number of object instances.
  • 描述:每次对该作用域下的Bean的请求都会创建新的实例:获取Bean(即通过pplicationContext.getBean等方法获取)及装配Bean(即通过@Autowired注入)都是新的对象实例
  • 场景:通常有状态的Bean使用该作用域

6.4  request

  • 描述:每次http请求会创建新的Bean实例,类似于prototype
  • 场景:一次http的请求和响应的共享Bean
  • 备注:限定SpringMVC中使用

6.5  session

  • 官方说明:Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid inthe context of a web-aware Spring ApplicationContext.
  • 描述:在一个http session中,定义一个Bean实例
  • 场景:用户回话的共享Bean, 比如:记录一个用户的登陆信息
  • 备注:限定SpringMVC中使用

6.6  application

  • 官方说明:Scopes a single bean definition to the lifecycle of a ServletContext.Only valid in the context of a web-aware Spring ApplicationContext.
  • 描述:在一个http servlet Context中,定义一个Bean实例
  • 场景:Web应用的上下文信息,比如:记录一个应用的共享信息
  • 备注:限定SpringMVC中使用

7.7  websocket:

  • 官方说明:Scopes a single bean definition to the lifecycle of a WebSocket.Only valid in thecontext of a web-aware Spring ApplicationContext.
  • 描述:在一个HTTP WebSocket的生命周期中,定义一个Bean实例
  • 场景:WebSocket的每次会话中,保存了一个Map结构的头信息,将用来包裹客户端消息头。第一次初始化后,直到WebSocket结束都是同一个Bean。
  • 备注:限定Spring WebSocket中使用
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
 
@Component
public class Users {
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    @Bean(name = "u1")
    public User user1() {
        User user = new User();
        user.setId(1);
        user.setName("Java"); // 【重点:名称是 Java】
        return user;
    }
}

@Scope 标签既可以修饰方法也可以修饰类,@Scope 有两种设置方式:

1. 直接设置值:@Scope("prototype")

2. 使用枚举设置:@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

七.Spring的启动流程 

1、启动容器

2、解析配置文件的内容,并创建bean

3、把对象放入容器当中

4、bean对象依赖装配

Bean 执行流程(Spring 执行流程):启动 Spring 容器 -> 实例化 Bean(分配内存空间,从无到

有) -> Bean 注册到 Spring 中(存操作) -> 将 Bean 装配到需要的类中(取操作)。

八.Bean的生命周期

bean的生命周期即对象从诞生到销毁的整个过程,我们把这个过程叫做一个对象的生命周期

把这个过程类比于买房的话就是如下

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/279699.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

win部署stable-diffusion

win部署stable-diffusion 1.环境2.模型3.使用4.效果 1.环境 首先下载stable-diffusion-webui&#xff0c;这个包了一层ui&#xff0c;特别好用。 git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git然后搭建conda环境。 这里的pytorch&#xff0c;自己去…

挑战Python100题(8)

100+ Python challenging programming exercises 8 Question 71 Please write a program which accepts basic mathematic expression from console and print the evaluation result. 请编写一个从控制台接受基本数学表达式的程序,并打印评估结果。 Example: If the follo…

集群部署篇--Redis 哨兵模式

文章目录 前言一、哨兵模式介绍&#xff1a;1.1 介绍&#xff1a;1.2 工作机制&#xff1a; 二、哨兵模式搭建&#xff1a;2. 1 redis 主从搭建&#xff1a;2.2 setinel 集群搭建&#xff1a;2.2.1 配置&#xff1a; sentinel.conf &#xff1a;2.2.2 运行容器&#xff1a;2.2.…

提升效率:使用注解实现精简而高效的Spring开发

IOC/DI注解开发 1.0 环境准备1.1 注解开发定义bean步骤1:删除原XML配置步骤2:Dao上添加注解步骤3:配置Spring的注解包扫描步骤4&#xff1a;运行程序步骤5:Service上添加注解步骤6:运行程序知识点1:Component等 1.2 纯注解开发模式1.2.1 思路分析1.2.2 实现步骤步骤1:创建配置类…

智能硬件(8)之蜂鸣器模块

学好开源硬件&#xff0c;不仅仅需要会编程就可以了&#xff0c;电路基础是很重要的&#xff1b;软件和硬件都玩的溜&#xff0c;才是高手&#xff0c;那么小编为了方便大家的学习&#xff0c;特别画了一块智能传感器板子&#xff0c;来带领大家学习电路基础&#xff0c;玩转智…

nodejs+vue网上书城图书销售商城系统io69w

功能介绍 该系统将采用B/S结构模式&#xff0c;使用Vue和ElementUI框架搭建前端页面&#xff0c;后端使用Nodejs来搭建服务器&#xff0c;并使用MySQL&#xff0c;通过axios完成前后端的交互 系统的主要功能包括首页、个人中心、用户管理、图书类型管理、图书分类管理、图书信…

[C++] : 贪心算法专题(第一部分)

1.柠檬水找零&#xff1a; 1.思路一&#xff1a; 柠檬水找零 class Solution { public:bool lemonadeChange(vector<int>& bills) {int file0;int ten 0;for(auto num:bills){if(num 5) file;else if(num 10){if(file > 0)file--,ten;elsereturn false;}else{i…

Python生成器 (Generators in Python)

Generators in Python 文章目录 Generators in PythonIntroduction 导言贯穿全文的几句话为什么 Python 有生成器Generator&#xff1f;如何获得生成器Generator&#xff1f;1. 生成器表达式 Generator Expression2. 使用yield定义生成器Generator 更多Generator应用实例表示无…

准备用vscode代替sourceinsight

vscode版本1.85.1 有的符号&#xff0c;sourceinsight解析不到。 看网上说vscode内置了ripgrep&#xff0c;但ctrlshiftf在文件里查找的时候&#xff0c;速度特别慢&#xff0c;根本不像ripgrep的速度。ripgrep的速度是很快的。 但今天再查询&#xff0c;速度又很快了&#x…

Large-Precision Sign using PBS

参考文献&#xff1a; [CLOT21] Chillotti I, Ligier D, Orfila J B, et al. Improved programmable bootstrapping with larger precision and efficient arithmetic circuits for TFHE[C]//Advances in Cryptology–ASIACRYPT 2021: 27th International Conference on the T…

前后端分离nodejs+vue+ElementUi网上订餐系统69b9

课题主要分为两大模块&#xff1a;即管理员模块和用户模块&#xff0c;主要功能包括个人中心、用户管理、菜品类型管理、菜品信息管理、留言反馈、在线交流、系统管理、订单管理等&#xff1b; 运行软件:vscode 前端nodejsvueElementUi 语言 node.js 框架&#xff1a;Express/k…

10.定时器各功能分析及编码

知识汇总&#xff1a; STM32的定时器有三种&#xff0c;高级定时器&#xff0c;通用定时器&#xff0c;基本定时器 就是功能多与少的差别&#xff0c;下面来逐个解释功能&#xff1a;在此之前&#xff0c;需要对几个概念有认知 几个概念&#xff1a; 1.定时器时钟频率&…

【论文笔记】Radar Fields: An Extension of Radiance Fields to SAR

原文链接&#xff1a;https://arxiv.org/abs/2312.12961 1. 引言 本文针对合成孔径雷达&#xff08;SAR&#xff09;的3D重建&#xff0c;提出雷达场&#xff0c;基于多个SAR对场景的测量学习体积模型。 3. 辐射场的介绍 NeRF将静态场景表达为连续的体积函数 F \mathcal{F}…

长城杯2021政企组-魔鬼凯撒的RC4茶室 WP

魔鬼凯撒的RC4茶室 知识点&#xff1a;UPX 移位密码 XOR 分析 查壳 32bit&#xff1b;UPX壳&#xff0c;upx -d直接脱。 查看主函数。 第一处输入Str1然后做一个比较。这里进去。 有个小技巧&#xff0c;这里传入的参数是Str字符串&#xff0c;但是原本IDA自动识别出来的…

智能监控平台/视频共享融合系统EasyCVR海康设备国标GB28181接入流程

TSINGSEE青犀视频监控汇聚平台EasyCVR可拓展性强、视频能力灵活、部署轻快&#xff0c;可支持的主流标准协议有国标GB28181、RTSP/Onvif、RTMP等&#xff0c;以及支持厂家私有协议与SDK接入&#xff0c;包括海康Ehome、海大宇等设备的SDK等。平台既具备传统安防视频监控的能力&…

shiro1.10版本后-IniSecurityManagerFactory过期失效

1、问题概述&#xff1f; 今天在研究了shiro的新版本shiro1.13.0版本&#xff0c;发现用了很长时间的IniSecurityManagerFactory工厂失效了。 从下图中可以看出&#xff0c;在新版本中IniSecurityManagerFactory被打上了过期线了。 那么问题来了&#xff0c;新版本如何使用呢…

Python 命令补全工具 argcomplete

1. 概述 在使用Python 命令或者 Python的命令行工具的时候&#xff0c;一个痛点是没有补全。比如python -m后面输入包名字&#xff0c;就没有提示&#xff0c;每次想运行一个http server的时候&#xff0c;都需要搜索一下http服务的包名。另外&#xff0c;像pip&#xff0c;pi…

Java注解学习,一文掌握@Autowired 和 @Resource 注解区别

&#x1f3c6;作者简介&#xff0c;普修罗双战士&#xff0c;一直追求不断学习和成长&#xff0c;在技术的道路上持续探索和实践。 &#x1f3c6;多年互联网行业从业经验&#xff0c;历任核心研发工程师&#xff0c;项目技术负责人。 &#x1f389;欢迎 &#x1f44d;点赞✍评论…

【前端面经】即时设计

目录 前言一面git 常见命令跨窗口通信vue 响应式原理发布订阅模式翻转二叉树Promise.all()扁平化数组面试官建议 二面Event Loop 原理Promise 相关css 描边方式requestAnimationReact 18 新特性JSX 相关react 输出两次函数式编程React 批处理机制http请求头有哪些本地存储性能优…

秒杀系统的设计思路(应对高并发,超卖等问题的解决思路)

首先我们先看一下设计秒杀系统时&#xff0c;我们应该考虑的问题。 解决方案&#xff1a; 一.页面静态化结合CDN内容分发 前端把能提前放入cdn服务器的东西都放进去&#xff0c;反正把所有能提升效率的步骤都做一下&#xff0c;减少真正秒杀时候服务器的压力。 秒杀活动的页面…
最新文章