Пример регулярного выражения Spring EL
Spring EL поддерживает регулярное выражение с использованием простого ключевого слова «matches», что действительно здорово! Например,
@Value("#{'100' matches '\\d+' }")
private boolean isDigit;
Он проверяет, является ли «100» допустимой цифрой, с помощью регулярного выражения «\d+».
Spring EL в аннотации
См. Следующие примеры регулярных выражений Spring EL, некоторые из которых смешаны с тернарным оператором, что делает Spring EL довольно гибким и мощным.
Пример ниже должен быть понятным.
package com.example.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("customerBean")
public class Customer {
// email regular expression
String emailRegEx = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)" +
"*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
// if this is a digit?
@Value("#{'100' matches '\\d+' }")
private boolean validDigit;
// if this is a digit + ternary operator
@Value("#{ ('100' matches '\\d+') == true ? " +
"'yes this is digit' : 'No this is not a digit' }")
private String msg;
// if this emailBean.emailAddress contains a valid email address?
@Value("#{emailBean.emailAddress matches customerBean.emailRegEx}")
private boolean validEmail;
//getter and setter methods, and constructor
}
package com.example.core;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("emailBean")
public class Email {
@Value("[email protected]")
String emailAddress;
//...
}
Выход
Customer [isDigit=true, msg=yes this is digit, isValidEmail=true]
Spring EL в XML
Смотрите эквивалентную версию в XML-файле определения компонента.
Скачать исходный код
Скачать -Spring3-EL-Regular-Expression-Example.zip (6 КБ)