Spring 专题
专题目录
您的位置:java > Spring专题 > Spring EL正则表达式实例
Spring EL正则表达式实例
作者:--    发布时间:2019-11-20
spring el支持正则表达式,可使用一个简单的关键词“matches”。如下实例,
@value("#{'100' matches '\\d+' }")
private boolean isdigit;
它测试'100'是否是通过正则表达式‘\\d+‘测试过的一个有效的数字。

spring el以注解的形式

请参阅下面的 spring el 正则表达式的例子,这里有部分掺入三元运算符,这使得 spring el 非常灵活,功能强大。
下面的例子应该是不言自明的。
package com.h3.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.h3.core;

import org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.component;

@component("emailbean")
public class email {

	@value("admin@h3.com")
	string emailaddress;

	//...
}

输出

customer [isdigit=true, msg=yes this is digit, isvalidemail=true]

spring el以xml的形式

请参阅在xml文件定义bean的等效版本。
<beans xmlns="http://www.springframework.org/schema/beans"
	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-3.0.xsd">

	<bean id="customerbean" class="com.h3.core.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="#{emailbean.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="emailbean" class="com.h3.core.email">
	  <property name="emailaddress" value="admin@h3.com" />
	</bean>

</beans>

参考

  1. spring el三元运算符(if-then-else)实例

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册