spring架構校正自訂註解

來源:互聯網
上載者:User

標籤:context   ***   element   參數   ted   target   img   turn   att   

起因:

  項目開發時遇到一個問題是對於金額類型的欄位,資料庫中格式一般為BigDecimal類型,兩位小數點,然後在介面定義中如果不定義成String類型的話,就不能使用@pattern註解限定格式,而在hibernate的校正裡面,沒有相關適合的註解使用來限定金額格式,所以需要自訂一個註解來對這類參數進行校正。如果在介面中傳入的參數值小數點後不止兩位,在mysql中進行插入的時候會自動進行剪下,如傳入1.315元,在入庫的時候該參數就可能被剪下成1.35元,最終入庫資料為1.35。

 

解決:自定一個Amount的註解來對金額相關欄位進行校正

1 自訂一個聲明類

package ****************;import javax.validation.Constraint;import javax.validation.Payload;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.FIELD, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Constraint(validatedBy=AmountValidator.class)public @interface Amount {    String message() default "{org.validation.constraints.Amount.message}";    Class<?>[] groups() default {};    Class<? extends Payload>[] payload() default {};}

2實現校正方式類   @Constraint(validatedBy=AmountValidator.class)中的  AmountValidator類

package *********;import javax.validation.ConstraintValidator;import javax.validation.ConstraintValidatorContext;import java.math.BigDecimal;import java.util.regex.Pattern;public class AmountValidator implements ConstraintValidator<Amount, BigDecimal> {    /**     * 表示金額的Regex     */    private String moneyReg = "^\\d+(\\.\\d{1,2})?$";    private Pattern moneyPattern = Pattern.compile(moneyReg);    @Override    public void initialize(Amount amount) {    }    @Override    public boolean isValid(BigDecimal value, ConstraintValidatorContext arg1) {        return moneyPattern.matcher(value.toString()).matches();    }}

然後在請求實體bean中需要校正的參數上加上 @Amount註解即可使用

3支援國際化(選)

在你的resource檔案夾下加上ValidationMessages.properties檔案和 ValidationMessages_zh_CN.properties檔案 

裡面自訂錯誤資訊,當瀏覽器語言被檢測為中文時,系統會尋找ValidationMessages_zh_CN.properties該檔案下的 

org.validation.constraints.Amount.message的值,
若無ValidationMessages_zh_CN.properties檔案,則會尋找預設檔案ValidationMessages.properties中
org.validation.constraints.Amount.message的值返回。

 

spring架構校正自訂註解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.