springBoot 配置接收 String 参数时自动去除前后空格
    		       		warning:
    		            这篇文章距离上次修改已过420天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot中,你可以通过自定义编辑器(Editor)或者使用@InitBinder注解来实现在绑定String参数时自动去除前后空格的功能。
下面是使用@InitBinder的方法:
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.stereotype.Controller;
 
@Controller
public class BaseController {
 
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
}这段代码会为所有Controller注册一个自定义编辑器,它会使用StringTrimmerEditor类,这个类继承自PropertyEditorSupport,用于修剪String参数的前后空格。参数true表示如果修剪后结果为空字符串,则使用null。
如果你想针对特定的Controller进行配置,可以将@InitBinder注解的使用与@ControllerAdvice结合使用,创建一个@ControllerAdvice类,然后只在该类中注册StringTrimmerEditor。
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
@Component
@ControllerAdvice
public class GlobalControllerAdvice {
 
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
}这样,所有Controller中的String参数在绑定时都会自动去除前后空格。
评论已关闭