温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Spring Boot中定制PropertyEditors方法

发布时间:2021-05-21 16:28:12 来源:亿速云 阅读:127 作者:Leah 栏目:编程语言

这篇文章给大家介绍怎么在Spring Boot中定制PropertyEditors方法,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

Isbn类:

package com.test.bookpub.utils;

public class Isbn {
  private String isbn;

  public Isbn(String isbn) {
    this.isbn = isbn;
  }
  public String getIsbn() {
    return isbn;
  }
}

IsbnEditor类,继承PropertyEditorSupport类,setAsText完成字符串到具体对象类型的转换,getAsText完成具体对象类型到字符串的转换。

package com.test.bookpub.utils;
import org.springframework.util.StringUtils;
import java.beans.PropertyEditorSupport;

public class IsbnEditor extends PropertyEditorSupport {
  @Override
  public void setAsText(String text) throws IllegalArgumentException {
    if (StringUtils.hasText(text)) {
      setValue(new Isbn(text.trim()));
    } else {
      setValue(null);
    }
  }
  @Override  public String getAsText() {
    Isbn isbn = (Isbn) getValue();
    if (isbn != null) {
      return isbn.getIsbn();
    } else {
      return "";
    }
  }
}

在BookController中增加initBinder函数,通过@InitBinder注解修饰,则可以针对每个web请求创建一个editor实例。

@InitBinderpublic 
void initBinder(WebDataBinder binder) {
  binder.registerCustomEditor(Isbn.class, new IsbnEditor());
}

修改BookController中对应的函数

@RequestMapping(value = "/{isbn}", method = RequestMethod.GET)
public Map<String, Object> getBook(@PathVariable Isbn isbn) {
  Book book = bookRepository.findBookByIsbn(isbn.getIsbn());
  Map<String, Object> response = new LinkedHashMap<>();
  response.put("message", "get book with isbn(" + isbn.getIsbn() +")");
  response.put("book", book);  return response;
}

springboot是什么

springboot一种全新的编程规范,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,SpringBoot也是一个服务于框架的框架,服务范围是简化配置文件。

关于怎么在Spring Boot中定制PropertyEditors方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI