几个 Spring 工具类的使用

本文介绍了Spring框架中几个非常实用的工具类,包括AnnotationUtils用于处理注解、HtmlUtils和JavaScriptUtils用于特殊字符转义及方法入参检测。此外还提到了用于web应用上下文操作的WebApplicationContextUtils及资源IO相关的Resource接口和FileUtils。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天简单记录下Spring中常用的工具类,通过这些工具类,我们可以很方便地实现某些功能。

1、AnnotationUtils注解工具

这个注解很强大,它可以扫描作用在类上、方法上的注解、也可以获取注解的某些属性和属性值。

public static void main(String[] args) throws NoSuchMethodException, SecurityException {
    // 获取作用在TestMethod类上的注解,注解的类型为RpcService,如果存在,则返回注解本身,不存在,则返回null
    RpcService annotation = AnnotationUtils.findAnnotation(TestMethod.class, RpcService.class);
    System.err.println(annotation);
    
    // 获取TestMethod类的around方法上的注解,注解类型为RpcService
    annotation = AnnotationUtils.findAnnotation(TestMethod.class.getMethod("around", String.class),
    		RpcService.class);
    System.err.println(annotation);
    // 获取对应类上声明的某个注解类型的属性值
    for (Annotation anno : TestMethod.class.getDeclaredAnnotations()) {
        if (anno instanceof RpcService) {
        	Map<String, Object> map = AnnotationUtils
        			.getAnnotationAttributes(TestMethod.class.getDeclaredAnnotation(RpcService.class));
        	for (Entry<String, Object> string : map.entrySet()) {
        		System.err.println(string.getKey() + " : " + string.getValue());
        	}
        }
    }
}
复制代码
2、特殊字符转义和方法入参检测工具类

spring提供了针对JavaScript、Html、SQL等语言的特殊符号处理,如html中的<,>等。

public static void main(String[] args) throws NoSuchMethodException, SecurityException {
    String specialStr = "<div id=\"testDiv\">test1;test2</div>";
    String str1 = HtmlUtils.htmlEscape(specialStr);
    System.out.println(str1);
    String decode = HtmlUtils.htmlUnescape(specialStr);
    System.err.println(decode);
    
    String js = JavaScriptUtils.javaScriptEscape("\";alert();j=\"");
    System.err.println(js);
}
复制代码

输出

&lt;div id=&quot;testDiv&quot;&gt;test1;test2&lt;/div&gt;
<div id="testDiv">test1;test2</div>
\";alert();j=\"
复制代码

除了上面的工具类,还有web相关的WebApplicationContextUtils来获取web应用上下文及相关属性,还有和资源io相关的Resource接口、FileUtils等可以实现文件加载和文件拷贝。

参考文章:

看Spring工具类一文,附自己的使用心得 Spring常用工具类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值