程序员scholar 程序员scholar
首页
  • Java 基础

    • JavaSE
    • JavaIO
    • JavaAPI速查
  • Java 高级

    • JUC
    • JVM
    • Java新特性
    • 设计模式
  • Web 开发

    • Servlet
    • Java网络编程
  • Web 标准

    • HTML
    • CSS
    • JavaScript
  • 前端框架

    • Vue2
    • Vue3
    • Vue3 + TS
    • 微信小程序
    • uni-app
  • 工具与库

    • jQuery
    • Ajax
    • Axios
    • Webpack
    • Vuex
    • WebSocket
    • 第三方登录
  • 后端与语言扩展

    • ES6
    • Typescript
    • node.js
  • Element-UI
  • Apache ECharts
  • 数据结构
  • HTTP协议
  • HTTPS协议
  • 计算机网络
  • Linux常用命令
  • Windows常用命令
  • SQL数据库

    • MySQL
    • MySQL速查
  • NoSQL数据库

    • Redis
    • ElasticSearch
  • 数据库

    • MyBatis
    • MyBatis-Plus
  • 消息中间件

    • RabbitMQ
  • 服务器

    • Nginx
  • Spring框架

    • Spring6
    • SpringMVC
    • SpringBoot
    • SpringSecurity
  • SpringCould微服务

    • SpringCloud基础
    • 微服务之DDD架构思想
  • 日常必备

    • 开发常用工具包
    • Hutoll工具包
    • IDEA常用配置
    • 开发笔记
    • 日常记录
    • 项目部署
    • 网站导航
    • 产品学习
    • 英语学习
  • 代码管理

    • Maven
    • Git教程
    • Git小乌龟教程
  • 运维工具

    • Docker
    • Jenkins
    • Kubernetes
  • 算法笔记

    • 算法思想
    • 刷题笔记
  • 面试问题常见

    • 十大经典排序算法
    • 面试常见问题集锦
关于
GitHub (opens new window)
首页
  • Java 基础

    • JavaSE
    • JavaIO
    • JavaAPI速查
  • Java 高级

    • JUC
    • JVM
    • Java新特性
    • 设计模式
  • Web 开发

    • Servlet
    • Java网络编程
  • Web 标准

    • HTML
    • CSS
    • JavaScript
  • 前端框架

    • Vue2
    • Vue3
    • Vue3 + TS
    • 微信小程序
    • uni-app
  • 工具与库

    • jQuery
    • Ajax
    • Axios
    • Webpack
    • Vuex
    • WebSocket
    • 第三方登录
  • 后端与语言扩展

    • ES6
    • Typescript
    • node.js
  • Element-UI
  • Apache ECharts
  • 数据结构
  • HTTP协议
  • HTTPS协议
  • 计算机网络
  • Linux常用命令
  • Windows常用命令
  • SQL数据库

    • MySQL
    • MySQL速查
  • NoSQL数据库

    • Redis
    • ElasticSearch
  • 数据库

    • MyBatis
    • MyBatis-Plus
  • 消息中间件

    • RabbitMQ
  • 服务器

    • Nginx
  • Spring框架

    • Spring6
    • SpringMVC
    • SpringBoot
    • SpringSecurity
  • SpringCould微服务

    • SpringCloud基础
    • 微服务之DDD架构思想
  • 日常必备

    • 开发常用工具包
    • Hutoll工具包
    • IDEA常用配置
    • 开发笔记
    • 日常记录
    • 项目部署
    • 网站导航
    • 产品学习
    • 英语学习
  • 代码管理

    • Maven
    • Git教程
    • Git小乌龟教程
  • 运维工具

    • Docker
    • Jenkins
    • Kubernetes
  • 算法笔记

    • 算法思想
    • 刷题笔记
  • 面试问题常见

    • 十大经典排序算法
    • 面试常见问题集锦
关于
GitHub (opens new window)
npm

(进入注册为作者充电)

  • 快速入门

  • 克隆

  • 类型转换

  • 日期时间

  • IO流相关

  • 工具类

  • 语言特性

  • JavaBean

  • 集合类

  • Map

  • Codec编码

  • 文本操作

  • 注解

  • 比较器

  • 异常

  • 数学

  • 线程和并发

  • 图片

  • 网络

  • 源码编译

  • 配置文件

  • 日志

  • 缓存

  • JSON

  • 加密解密

  • DFA查找

  • HTTP客户端

  • 定时任务

  • 扩展

    • Servlet 工具类 - `ServletUtil`
    • 二维码工具 - `QrCodeUtil`
    • 邮件工具 - `MailUtil`
    • Cglib 工具 - `CglibUtil`
    • Emoji 工具 - `EmojiUtil`
    • FTP 客户端封装 - `Ftp`
    • 简易FTP服务器 - `SimpleFtpServer`
    • SFTP封装 - `Sftp`
    • Jsch工具 - `JschUtil`
    • Spring工具 - `SpringUtil`
      • 依赖引入
      • 1. 注册 SpringUtil
        • 方法一:使用 @ComponentScan 扫描
        • 方法二:使用 @Import 导入
      • 2. 获取指定 Bean
        • 示例:定义一个 Bean 并获取
      • 3. 动态获取所有 Bean
        • 示例:获取所有指定类型的 Bean
      • 4. 实际场景示例
    • 中文分词封装 - `TokenizerUtil`
    • 160压缩封装 - `CompressUtil`
    • 拼音工具 - `PinyinUtil`
    • 表达式引擎封装 - `ExpressionUtil`
    • 模板引擎封装 - `TemplateUtil`
  • 切面

  • 脚本

  • Office文档操作

  • 系统调用

  • 图形验证码

  • 网络Socket

  • JWT

  • Hutoll
  • 扩展
scholar
2024-08-20
目录

Spring工具 - SpringUtil

# Spring工具 - SpringUtil


介绍

在 Spring Boot 中,依赖注入(Dependency Injection)可以很方便地获取 Bean。但是在一些工具化场景中,尤其是静态方法或独立工具类中,我们通常无法直接使用 Spring 的依赖注入。这时,Hutool 提供的 SpringUtil 工具类,可以帮助我们动态获取 Spring 容器中的 Bean,极大地方便了开发。


# 依赖引入

SpringUtil 属于 Hutool 的 extra 模块,因此在使用时需要引入 Hutool 的依赖:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-extra</artifactId>
    <version>${hutool.version}</version>
</dependency>
1
2
3
4
5

# 1. 注册 SpringUtil

在 Spring Boot 项目中,我们需要将 SpringUtil 注册到 Spring 容器中,以便在全局范围内使用。通常有两种方式可以进行注册:

# 方法一:使用 @ComponentScan 扫描

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {"cn.hutool.extra.spring"})
public class AppConfig {
    // 通过扫描 Hutool 包,将 SpringUtil 自动注册到 Spring 容器中
}
1
2
3
4
5
6
7
8

# 方法二:使用 @Import 导入

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(SpringUtil.class)
public class AppConfig {
    // 直接导入 SpringUtil 类,将其注册到 Spring 容器中
}
1
2
3
4
5
6
7
8
9

实际开发场景:

  • 在独立工具类、静态方法或需要手动获取 Spring 容器中的 Bean 时,可以通过 SpringUtil 动态获取。

# 2. 获取指定 Bean

使用 SpringUtil 可以通过 Bean 名称、类型或两者结合的方式获取 Spring 容器中的 Bean。

# 示例:定义一个 Bean 并获取

首先定义一个 Bean:

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class DemoConfig {
    
    @Bean(name = "testDemo")
    public Demo generateDemo() {
        Demo demo = new Demo();
        demo.setId(12345);
        demo.setName("test");
        return demo;
    }
}

class Demo {
    private long id;
    private String name;

    // Getters and Setters
    public long getId() { return id; }
    public void setId(long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

使用 SpringUtil 获取 Bean:

import cn.hutool.extra.spring.SpringUtil;

public class SpringUtilExample {
    public static void main(String[] args) {
        // 通过名称获取 Bean
        Demo demo = SpringUtil.getBean("testDemo");

        System.out.println("Bean ID: " + demo.getId()); // 输出:Bean ID: 12345
        System.out.println("Bean Name: " + demo.getName()); // 输出:Bean Name: test
    }
}
1
2
3
4
5
6
7
8
9
10
11

代码解析:

  • SpringUtil.getBean(String beanName):根据 Bean 名称获取 Bean 实例。

    • beanName:Spring 容器中定义的 Bean 名称。
  • SpringUtil.getBean(Class<T> beanClass):根据 Bean 类型获取 Bean 实例。

    • beanClass:Bean 的 Class 类型。
  • SpringUtil.getBean(String beanName, Class<T> beanClass):根据名称和类型组合获取 Bean 实例,适用于同类型 Bean 多实例的情况。

实际应用场景:

  • 在工具类或非 Spring 托管的类中,需要动态获取 Bean 时使用。
  • 在静态方法中需要访问 Spring 容器时,可以通过 SpringUtil 获取依赖。

# 3. 动态获取所有 Bean

除了获取单个 Bean 外,还可以获取 Spring 容器中所有指定类型的 Bean。

# 示例:获取所有指定类型的 Bean

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.context.ApplicationContext;

import java.util.Map;

public class SpringUtilExample {
    public static void main(String[] args) {
        // 获取所有 Demo 类型的 Bean
        Map<String, Demo> demoBeans = SpringUtil.getBeansOfType(Demo.class);

        // 输出所有 Demo Bean
        demoBeans.forEach((name, bean) -> {
            System.out.println("Bean Name: " + name + ", Bean Value: " + bean.getName());
        });
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

代码解析:

  • SpringUtil.getBeansOfType(Class<T> type):获取所有指定类型的 Bean 实例,并返回一个包含名称和实例的 Map。
    • type:指定要获取的 Bean 类型。

实际应用场景:

  • 在需要批量处理某类 Bean 时,如对某个接口的所有实现类进行统一操作。
  • 动态获取并遍历所有符合条件的 Bean 实例。

# 4. 实际场景示例

假设我们有一个工具类需要发送邮件,但在工具类中我们无法直接使用依赖注入。我们可以通过 SpringUtil 获取邮件服务 Bean:

public class EmailSenderUtil {

    public static void sendEmail(String recipient, String subject, String content) {
        MailService mailService = SpringUtil.getBean(MailService.class);
        mailService.send(recipient, subject, content);
    }
}
1
2
3
4
5
6
7

在调用时,无需担心依赖注入问题,SpringUtil 自动从 Spring 容器中获取 MailService。


总结

SpringUtil 是一个简化 Spring Bean 动态获取的工具,特别适合在工具类、静态方法和非 Spring 托管的类中使用。它通过简单的 API,使得在任何地方都能轻松获取到 Spring 容器中的 Bean,从而极大提高了开发效率。

编辑此页 (opens new window)
上次更新: 2024/12/28, 18:32:08
Jsch工具 - `JschUtil`
中文分词封装 - `TokenizerUtil`

← Jsch工具 - `JschUtil` 中文分词封装 - `TokenizerUtil`→

Theme by Vdoing | Copyright © 2019-2025 程序员scholar
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式