SpringEL-正则表达式
Spring EL支持正则表达式,可使用一个简单的关键词“matches”。
一、编写Bean类
Email类:
package com.yiidian.domain;
/**
*
* @author http://www.yiidian.com
*
*/
public class Email {
private String emailAddress;
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
Customer类:
package com.yiidian.domain;
import java.io.Serializable;
/**
*
* @author http://www.yiidian.com
*
*/
public class Customer implements Serializable {
// 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?
private boolean validDigit;
// if this is a digit + ternary operator
private String msg;
// if this emailBean.emailAddress contains a valid email address?
private boolean validEmail;
@Override
public String toString() {
return "Customer [validDigit="
+ validDigit + ", msg=" + msg + ", validEmail=" + validEmail
+ "]";
}
public String getEmailRegEx() {
return emailRegEx;
}
public void setEmailRegEx(String emailRegEx) {
this.emailRegEx = emailRegEx;
}
public boolean isValidDigit() {
return validDigit;
}
public void setValidDigit(boolean validDigit) {
this.validDigit = validDigit;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public boolean isValidEmail() {
return validEmail;
}
public void setValidEmail(boolean validEmail) {
this.validEmail = validEmail;
}
}
二、配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="customer" class="com.yiidian.domain.Customer">
<property name="validDigit" value="#{'100' matches '\d+' }" />
<property name="msg"
value="#{ ('100' matches '\d+') == true ? 'yes this is digit' : 'No this is not a digit' }" />
<property name="validEmail"
value="#{email.emailAddress matches '^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$' }" />
</bean>
<bean id="email" class="com.yiidian.domain.Email">
<property name="emailAddress" value="admin@yiidian.com" />
</bean>
</beans>
三、编写测试类
package com.yiidian.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yiidian.domain.Customer;
/**
* @author http://www.yiidian.com
*
*/
public class Demo1 {
@Test
public void test1() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Customer customer = (Customer)context.getBean("customer");
System.out.println(customer);
}
}
四、运行结果
热门文章
优秀文章