springboot以其强大的自动配置和丰富的生态系统成为java开发的首选框架。
除了核心功能外,springboot及其依赖的spring框架还包含大量实用工具类,它们可以显著简化日常开发工作。
本文将介绍49个常用工具类,并通过简洁的代码示例展示它们的基本用法。
字符串处理工具类
1. stringutils
import org.springframework.util.stringutils;
// 检查字符串是否为空
boolean isempty = stringutils.isempty(null); // true
boolean isempty2 = stringutils.isempty(""); // true
// 检查字符串是否有文本内容
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"); // true4. 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!"集合和数组工具类
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;
// 创建高并发场景下的引用map (类似weakhashmap但线程安全)
map<string, object> cache = new concurrentreferencehashmap<>();
cache.put("key1", new largeobject());8. systempropertyutils
import org.springframework.util.systempropertyutils;
// 解析含系统属性的字符串
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");
// 调用方法
method method = reflectionutils.findmethod(person.class, "setage", int.class);
reflectionutils.makeaccessible(method);
reflectionutils.invokemethod(method, person, 30);
// 字段回调
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;
// 复制属性
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;
// 复制文件内容
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"));
// 流复制
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"));
// 复制目录
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相关工具类
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); // 从请求中获取参数 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;
// 构建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转义
string escaped = htmlutils.htmlescape("<script>alert('xss')</script>");
// <script>alert('xss')</script>
// html反转义
string unescaped = htmlutils.htmlunescape("<b>bold</b>");
// <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;
// 数字转换
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");
// 执行任务1
thread.sleep(100);
watch.stop();
watch.start("phase2");
// 执行任务2
thread.sleep(200);
watch.stop();
// 输出报告
system.out.println(watch.prettyprint());
system.out.println("total time: " + watch.gettotaltimemillis() + "ms");安全相关工具
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和数据转换工具
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转换器 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结果
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; // 类型转换 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;
// 根据文件名推断媒体类型
optional<mediatype> mediatype = mediatypefactory.getmediatype("document.pdf");
// application/pdf41. 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;
// 创建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;
// 发布事件
applicationeventpublisher publisher = /* 获取发布器 */;
publisher.publishevent(new customevent("something happened"));45. localecontextholder
import org.springframework.context.i18n.localecontextholder; import java.util.locale; // 获取/设置当前语言环境 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; // 创建代理 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();总结
这些工具类涵盖了java开发中的大部分常见场景,从基础的字符串处理到高级的反射操作,从文件io到安全加密,从web开发到性能监控。
熟练掌握这些工具类可以显著提高开发效率,减少样板代码,并帮助编写更健壮的应用程序。
在日常开发中,建议养成查看spring和springboot文档的习惯,挖掘更多有用的工具类。
以上就是springboot中内置的49个常用工具类使用的详细内容,更多关于springboot内置工具类的资料请关注代码网其它相关文章!
发表评论