几个 Spring 工具类的使用

1,587 阅读1分钟

今天简单记录下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常用工具类