最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot中內(nèi)置的49個常用工具類使用

 更新時間:2025年04月27日 10:58:57   作者:風(fēng)象南  
SpringBoot以其強大的自動配置和豐富的生態(tài)系統(tǒng)成為Java開發(fā)的首選框架,本文將介紹49個常用工具類,并通過簡潔的代碼示例展示它們的基本用法,希望對大家有一定的幫助

SpringBoot以其強大的自動配置和豐富的生態(tài)系統(tǒng)成為Java開發(fā)的首選框架。

除了核心功能外,SpringBoot及其依賴的Spring框架還包含大量實用工具類,它們可以顯著簡化日常開發(fā)工作。

本文將介紹49個常用工具類,并通過簡潔的代碼示例展示它們的基本用法。

字符串處理工具類

1. StringUtils

import org.springframework.util.StringUtils;

// 檢查字符串是否為空
boolean isEmpty = StringUtils.isEmpty(null);  // true
boolean isEmpty2 = StringUtils.isEmpty("");  // true

// 檢查字符串是否有文本內(nèi)容
boolean hasText = StringUtils.hasText("  ");  // false
boolean hasText2 = StringUtils.hasText("hello");  // true

// 分割字符串
String[] parts = StringUtils.tokenizeToStringArray("a,b,c", ",");

// 清除首尾空白
String trimmed = StringUtils.trimWhitespace("  hello  ");  // "hello"

2. AntPathMatcher

import org.springframework.util.AntPathMatcher;

AntPathMatcher matcher = new AntPathMatcher();
boolean match1 = matcher.match("/users/*", "/users/123");  // true
boolean match2 = matcher.match("/users/**", "/users/123/orders");  // true
boolean match3 = matcher.match("/user?", "/user1");  // true

// 提取路徑變量
Map<String, String> vars = matcher.extractUriTemplateVariables(
    "/users/{id}", "/users/42");  // {id=42}

3. PatternMatchUtils

import org.springframework.util.PatternMatchUtils;

boolean matches1 = PatternMatchUtils.simpleMatch("user*", "username");  // true
boolean matches2 = PatternMatchUtils.simpleMatch("user?", "user1");  // true
boolean matches3 = PatternMatchUtils.simpleMatch(
    new String[]{"user*", "admin*"}, "username");  // true

4. PropertyPlaceholderHelper

import org.springframework.util.PropertyPlaceholderHelper;

PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}");
Properties props = new Properties();
props.setProperty("name", "World");
props.setProperty("greeting", "Hello ${name}!");

String result = helper.replacePlaceholders("${greeting}", props::getProperty);
// "Hello World!"

集合和數(shù)組工具類

5. CollectionUtils

import org.springframework.util.CollectionUtils;

// 檢查集合是否為空
boolean isEmpty = CollectionUtils.isEmpty(null);  // true
boolean isEmpty2 = CollectionUtils.isEmpty(Collections.emptyList());  // true

// 集合操作
List<String> list1 = Arrays.asList("a", "b", "c");
List<String> list2 = Arrays.asList("b", "c", "d");
Collection<String> intersection = CollectionUtils.intersection(list1, list2);  // [b, c]

// 合并集合
List<String> target = new ArrayList<>();
CollectionUtils.mergeArrayIntoCollection(new String[]{"a", "b"}, target);

6. MultiValueMap

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("colors", "red");
map.add("colors", "blue");
map.add("sizes", "large");

List<String> colors = map.get("colors");  // [red, blue]

7. ConcurrentReferenceHashMap

import org.springframework.util.ConcurrentReferenceHashMap;

// 創(chuàng)建高并發(fā)場景下的引用Map (類似WeakHashMap但線程安全)
Map<String, Object> cache = new ConcurrentReferenceHashMap<>();
cache.put("key1", new LargeObject());

8. SystemPropertyUtils

import org.springframework.util.SystemPropertyUtils;

// 解析含系統(tǒng)屬性的字符串
String javaHome = SystemPropertyUtils.resolvePlaceholders("${java.home}");
String pathWithDefault = SystemPropertyUtils.resolvePlaceholders(
    "${unknown.property:default}");  // "default"

反射和類處理工具

9. ReflectionUtils

import org.springframework.util.ReflectionUtils;

// 獲取類的字段
Field field = ReflectionUtils.findField(Person.class, "name");
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, person, "John");

// 調(diào)用方法
Method method = ReflectionUtils.findMethod(Person.class, "setAge", int.class);
ReflectionUtils.makeAccessible(method);
ReflectionUtils.invokeMethod(method, person, 30);

// 字段回調(diào)
ReflectionUtils.doWithFields(Person.class, field -> {
    System.out.println(field.getName());
});

10. ClassUtils

import org.springframework.util.ClassUtils;

// 獲取類名
String shortName = ClassUtils.getShortName("org.example.MyClass");  // "MyClass"

// 檢查類是否存在
boolean exists = ClassUtils.isPresent("java.util.List", null);  // true

// 獲取所有接口
Class<?>[] interfaces = ClassUtils.getAllInterfaces(ArrayList.class);

// 獲取用戶定義的類加載器
ClassLoader classLoader = ClassUtils.getDefaultClassLoader();

11. MethodInvoker

import org.springframework.util.MethodInvoker;

MethodInvoker invoker = new MethodInvoker();
invoker.setTargetObject(new MyService());
invoker.setTargetMethod("calculateTotal");
invoker.setArguments(new Object[]{100, 0.2});
invoker.prepare();
Object result = invoker.invoke();

12. BeanUtils

import org.springframework.beans.BeanUtils;

// 復(fù)制屬性
Person source = new Person("John", 30);
Person target = new Person();
BeanUtils.copyProperties(source, target);

// 實例化類
Person newPerson = BeanUtils.instantiateClass(Person.class);

// 查找方法
Method method = BeanUtils.findMethod(Person.class, "setName", String.class);

I/O和資源工具

13. FileCopyUtils

import org.springframework.util.FileCopyUtils;

// 復(fù)制文件內(nèi)容
byte[] bytes = FileCopyUtils.copyToByteArray(new File("input.txt"));
FileCopyUtils.copy(bytes, new File("output.txt"));

// 讀取文本
String content = FileCopyUtils.copyToString(
    new InputStreamReader(new FileInputStream("input.txt"), "UTF-8"));

// 流復(fù)制
FileCopyUtils.copy(inputStream, outputStream);

14. ResourceUtils

import org.springframework.util.ResourceUtils;

// 獲取文件
File file = ResourceUtils.getFile("classpath:config.properties");

// 檢查是否是URL
boolean isUrl = ResourceUtils.isUrl("http://example.com");

// 獲取URL
URL url = ResourceUtils.getURL("classpath:data.json");

15. StreamUtils

import org.springframework.util.StreamUtils;

// 流操作
byte[] data = StreamUtils.copyToByteArray(inputStream);
String text = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
StreamUtils.copy(inputStream, outputStream);
StreamUtils.copy("Hello", StandardCharsets.UTF_8, outputStream);

16. FileSystemUtils

import org.springframework.util.FileSystemUtils;

// 刪除目錄
boolean deleted = FileSystemUtils.deleteRecursively(new File("/tmp/test"));

// 復(fù)制目錄
FileSystemUtils.copyRecursively(new File("source"), new File("target"));

17. ResourcePatternUtils

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

// 獲取匹配資源
Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(
    new PathMatchingResourcePatternResolver())
    .getResources("classpath*:META-INF/*.xml");

Web相關(guān)工具類

18. WebUtils

import org.springframework.web.util.WebUtils;
import javax.servlet.http.HttpServletRequest;

// 獲取Cookie
Cookie cookie = WebUtils.getCookie(request, "sessionId");

// 獲取請求路徑
String path = WebUtils.getLookupPathForRequest(request);

// 從請求中獲取參數(shù)
int pageSize = WebUtils.getIntParameter(request, "pageSize", 10);

19. UriUtils

import org.springframework.web.util.UriUtils;

// 編解碼URI組件
String encoded = UriUtils.encodePathSegment("path with spaces", "UTF-8");
String decoded = UriUtils.decode(encoded, "UTF-8");

20. UriComponentsBuilder

import org.springframework.web.util.UriComponentsBuilder;

// 構(gòu)建URI
URI uri = UriComponentsBuilder.fromHttpUrl("http://example.com")
    .path("/products")
    .queryParam("category", "books")
    .queryParam("sort", "price")
    .build()
    .toUri();

21. ContentCachingRequestWrapper

import org.springframework.web.util.ContentCachingRequestWrapper;
import javax.servlet.http.HttpServletRequest;

ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(request);
// 請求處理后
byte[] body = wrapper.getContentAsByteArray();

22. HtmlUtils

import org.springframework.web.util.HtmlUtils;

// HTML轉(zhuǎn)義
String escaped = HtmlUtils.htmlEscape("<script>alert('XSS')</script>");
// &lt;script&gt;alert('XSS')&lt;/script&gt;

// HTML反轉(zhuǎn)義
String unescaped = HtmlUtils.htmlUnescape("&lt;b&gt;Bold&lt;/b&gt;");
// <b>Bold</b>

驗證和斷言工具

23. Assert

import org.springframework.util.Assert;

// 常用斷言
Assert.notNull(object, "Object must not be null");
Assert.hasText(name, "Name must not be empty");
Assert.isTrue(amount > 0, "Amount must be positive");
Assert.notEmpty(items, "Items must not be empty");
Assert.state(isInitialized, "Service is not initialized");

24. ObjectUtils

import org.springframework.util.ObjectUtils;

// 對象工具
boolean isEmpty = ObjectUtils.isEmpty(null);  // true
boolean isEmpty2 = ObjectUtils.isEmpty(new String[0]);  // true

String nullSafe = ObjectUtils.nullSafeToString(null);  // "null"
boolean equals = ObjectUtils.nullSafeEquals(obj1, obj2);

// 默認值
String value = ObjectUtils.getOrDefault(null, "default");

25. NumberUtils

import org.springframework.util.NumberUtils;

// 數(shù)字轉(zhuǎn)換
Integer parsed = NumberUtils.parseNumber("42", Integer.class);
Double converted = NumberUtils.convertNumberToTargetClass(42, Double.class);

日期和時間工具

26. DateTimeUtils

import org.springframework.format.datetime.DateTimeFormatUtils;
import java.util.Date;

// 格式化日期
String formatted = DateTimeFormatUtils.getDateTimeInstance().format(new Date());

27. StopWatch

import org.springframework.util.StopWatch;

// 計時工具
StopWatch watch = new StopWatch("TaskName");
watch.start("phase1");
// 執(zhí)行任務(wù)1
Thread.sleep(100);
watch.stop();

watch.start("phase2");
// 執(zhí)行任務(wù)2
Thread.sleep(200);
watch.stop();

// 輸出報告
System.out.println(watch.prettyPrint());
System.out.println("Total time: " + watch.getTotalTimeMillis() + "ms");

安全相關(guān)工具

28. DigestUtils

import org.springframework.util.DigestUtils;

// MD5哈希
String md5 = DigestUtils.md5DigestAsHex("password".getBytes());

// 文件MD5
String fileMd5;
try (InputStream is = new FileInputStream("file.txt")) {
    fileMd5 = DigestUtils.md5DigestAsHex(is);
}

29. Base64Utils

import org.springframework.util.Base64Utils;

// Base64編解碼
byte[] data = "Hello World".getBytes();
String encoded = Base64Utils.encodeToString(data);
byte[] decoded = Base64Utils.decodeFromString(encoded);

30. CryptoUtils

import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;

// 文本加密
String password = "secret";
String salt = "deadbeef";
TextEncryptor encryptor = Encryptors.text(password, salt);
String encrypted = encryptor.encrypt("Message");
String decrypted = encryptor.decrypt(encrypted);

JSON和數(shù)據(jù)轉(zhuǎn)換工具

31. JsonUtils

import org.springframework.boot.json.JsonParser;
import org.springframework.boot.json.JsonParserFactory;

// JSON解析
JsonParser parser = JsonParserFactory.getJsonParser();
Map<String, Object> parsed = parser.parseMap("{"name":"John", "age":30}");
List<Object> parsedList = parser.parseList("[1, 2, 3]");

32. TypeUtils

import org.springframework.core.ResolvableType;

// 類型解析
ResolvableType type = ResolvableType.forClass(List.class);
ResolvableType elementType = type.getGeneric(0);

// 泛型類型處理
ResolvableType mapType = ResolvableType.forClassWithGenerics(
    Map.class, String.class, Integer.class);

33. MappingJackson2HttpMessageConverter

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import com.fasterxml.jackson.databind.ObjectMapper;

// 自定義JSON轉(zhuǎn)換器
ObjectMapper mapper = new ObjectMapper();
// 配置mapper
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(mapper);

其他實用工具

34. RandomStringUtils

import org.apache.commons.lang3.RandomStringUtils;

// 隨機字符串生成
String random = RandomStringUtils.randomAlphanumeric(10);
String randomLetters = RandomStringUtils.randomAlphabetic(8);
String randomNumeric = RandomStringUtils.randomNumeric(6);

35. CompletableFutureUtils

import java.util.concurrent.CompletableFuture;
import java.util.List;
import java.util.stream.Collectors;

// 合并多個CompletableFuture結(jié)果
List<CompletableFuture<String>> futures = /* 多個異步操作 */;
CompletableFuture<List<String>> allResults = CompletableFuture.allOf(
    futures.toArray(new CompletableFuture[0]))
    .thenApply(v -> futures.stream()
        .map(CompletableFuture::join)
        .collect(Collectors.toList()));

36. CacheControl

import org.springframework.http.CacheControl;
import java.util.concurrent.TimeUnit;

// 緩存控制
CacheControl cacheControl = CacheControl.maxAge(1, TimeUnit.HOURS)
    .noTransform()
    .mustRevalidate();

String headerValue = cacheControl.getHeaderValue();

37. AnnotationUtils

import org.springframework.core.annotation.AnnotationUtils;

// 查找注解
Component annotation = AnnotationUtils.findAnnotation(MyClass.class, Component.class);

// 獲取注解屬性
String value = AnnotationUtils.getValue(annotation, "value").toString();

// 合并注解
Component mergedAnnotation = AnnotationUtils.synthesizeAnnotation(
    annotation, MyClass.class);

38. DefaultConversionService

import org.springframework.core.convert.support.DefaultConversionService;

// 類型轉(zhuǎn)換
DefaultConversionService conversionService = new DefaultConversionService();
String strValue = "42";
Integer intValue = conversionService.convert(strValue, Integer.class);

39. HeaderUtils

import org.springframework.http.HttpHeaders;

// HTTP頭處理
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
headers.setContentLength(1024);
headers.setCacheControl("max-age=3600");

40. MediaTypeFactory

import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import java.util.Optional;

// 根據(jù)文件名推斷媒體類型
Optional<MediaType> mediaType = MediaTypeFactory.getMediaType("document.pdf");
// application/pdf

41. MimeTypeUtils

import org.springframework.util.MimeTypeUtils;

// MIME類型常量和解析
boolean isCompatible = MimeTypeUtils.APPLICATION_JSON.isCompatibleWith(
    MimeTypeUtils.APPLICATION_JSON_UTF8);

42. WebClientUtils

import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;

// 創(chuàng)建WebClient
WebClient webClient = WebClient.builder()
    .baseUrl("https://api.example.com")
    .defaultHeader("Authorization", "Bearer token")
    .filter(ExchangeFilterFunction.ofRequestProcessor(
        clientRequest -> {
            // 請求處理
            return Mono.just(clientRequest);
        }))
    .build();

43. PropertySourceUtils

import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;

// 添加屬性源
StandardEnvironment env = new StandardEnvironment();
Map<String, Object> map = new HashMap<>();
map.put("app.name", "MyApp");
env.getPropertySources().addFirst(new MapPropertySource("my-properties", map));

44. EventPublishingUtils

import org.springframework.context.ApplicationEventPublisher;

// 發(fā)布事件
ApplicationEventPublisher publisher = /* 獲取發(fā)布器 */;
publisher.publishEvent(new CustomEvent("Something happened"));

45. LocaleContextHolder

import org.springframework.context.i18n.LocaleContextHolder;
import java.util.Locale;

// 獲取/設(shè)置當(dāng)前語言環(huán)境
Locale currentLocale = LocaleContextHolder.getLocale();
LocaleContextHolder.setLocale(Locale.FRENCH);

46. AopUtils

import org.springframework.aop.support.AopUtils;

// AOP工具方法
boolean isAopProxy = AopUtils.isAopProxy(bean);
boolean isCglibProxy = AopUtils.isCglibProxy(bean);
Class<?> targetClass = AopUtils.getTargetClass(bean);

47. ProxyUtils

import org.springframework.aop.framework.ProxyFactory;

// 創(chuàng)建代理
ProxyFactory factory = new ProxyFactory(targetObject);
factory.addInterface(MyInterface.class);
factory.addAdvice(new MyMethodInterceptor());
MyInterface proxy = (MyInterface) factory.getProxy();

48. ClassPathScanningCandidateComponentProvider

import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;

// 掃描類路徑
ClassPathScanningCandidateComponentProvider scanner = 
    new ClassPathScanningCandidateComponentProvider(true);
scanner.addIncludeFilter(new AnnotationTypeFilter(Component.class));
Set<BeanDefinition> beans = scanner.findCandidateComponents("org.example");

49. YamlUtils

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;

// 解析YAML文件
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource("application.yml"));
Properties properties = yaml.getObject();

總結(jié)

這些工具類涵蓋了Java開發(fā)中的大部分常見場景,從基礎(chǔ)的字符串處理到高級的反射操作,從文件IO到安全加密,從Web開發(fā)到性能監(jiān)控。

熟練掌握這些工具類可以顯著提高開發(fā)效率,減少樣板代碼,并幫助編寫更健壯的應(yīng)用程序。

在日常開發(fā)中,建議養(yǎng)成查看Spring和SpringBoot文檔的習(xí)慣,挖掘更多有用的工具類。

以上就是SpringBoot中內(nèi)置的49個常用工具類使用的詳細內(nèi)容,更多關(guān)于SpringBoot內(nèi)置工具類的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 詳解Mybatis-plus(MP)中CRUD操作保姆級筆記

    詳解Mybatis-plus(MP)中CRUD操作保姆級筆記

    本文主要介紹了Mybatis-plus(MP)中CRUD操作保姆級筆記,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • Spring Boot示例代碼整合Redis詳解

    Spring Boot示例代碼整合Redis詳解

    SpringBoot對常用的數(shù)據(jù)庫支持外,對NoSQL 數(shù)據(jù)庫也進行了封裝自動化,下面這篇文章主要給大家介紹了關(guān)于springboot使用redis的詳細步驟,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-06-06
  • java對于JSON的解析方法舉例詳解

    java對于JSON的解析方法舉例詳解

    在編寫應(yīng)用時,我們經(jīng)常要解析JSON,下面這篇文章主要給大家介紹了關(guān)于java對于JSON的解析方法,文中通過代碼示例介紹的非常詳細,需要的朋友可以參考下
    2023-09-09
  • idea 設(shè)置支持ES6語法的操作

    idea 設(shè)置支持ES6語法的操作

    這篇文章主要介紹了idea設(shè)置支持ES6語法的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • 關(guān)于批量插入或更新數(shù)據(jù)(MyBatis-plus框架)

    關(guān)于批量插入或更新數(shù)據(jù)(MyBatis-plus框架)

    這篇文章主要介紹了關(guān)于批量插入或更新數(shù)據(jù)(MyBatis-plus框架),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Spring?JPA?find分頁示例詳解

    Spring?JPA?find分頁示例詳解

    這篇文章主要為大家介紹了Spring?JPA?find分頁示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-04-04
  • Java中的ArrayList和線性表用法及說明

    Java中的ArrayList和線性表用法及說明

    文章介紹了線性表及其常見實現(xiàn)方式,包括順序表和鏈表,重點討論了順序表的實現(xiàn)細節(jié),如接口實現(xiàn)、增刪查改操作、內(nèi)存管理等,同時,文章還簡要介紹了ArrayList的概念及其在Java集合框架中的應(yīng)用,包括ArrayList的構(gòu)造、常見方法和遍歷方式
    2025-12-12
  • 從千千靜聽歌詞服務(wù)器獲取lrc歌詞示例分享

    從千千靜聽歌詞服務(wù)器獲取lrc歌詞示例分享

    這篇文章主要介紹了使用PHP從千千靜聽歌詞服務(wù)器獲取lrc歌詞的方法,大家參考使用吧
    2014-01-01
  • Java Spring JdbcTemplate基本使用詳解

    Java Spring JdbcTemplate基本使用詳解

    JDBC已經(jīng)能夠滿足大部分用戶最基本的需求,但是在使用JDBC時,必須自己來管理數(shù)據(jù)庫資源如:獲取PreparedStatement,設(shè)置SQL語句參數(shù),關(guān)閉連接等步驟
    2021-10-10
  • Spring中filter過濾器的定義方法

    Spring中filter過濾器的定義方法

    這篇文章主要介紹了Spring中filter過濾器的定義方法,Filter 程序是一個實現(xiàn)了特殊接口的 Java 類,與 Servlet 類似,也是由 Servlet 容器進行調(diào)用和執(zhí)行的,需要的朋友可以參考下
    2023-08-08

最新評論

苏尼特左旗| 信丰县| 广州市| 兴海县| 牙克石市| 章丘市| 平塘县| 周口市| 石屏县| 湘潭市| 淄博市| 班玛县| 邯郸县| 萨嘎县| 永康市| 普格县| 高碑店市| 江陵县| 容城县| 永福县| 怀柔区| 鸡西市| 东兰县| 台南市| 康保县| 容城县| 安塞县| 山阳县| 东方市| 施甸县| 普洱| 阳城县| 搜索| 库车县| 固原市| 开鲁县| 龙胜| 长宁区| 定兴县| 衢州市| 舒兰市|