Spring spel regex tutorial

Spring SpEL:

The SpEL stands for Spring Expression Language. It is a powerful expression language which supports querying and manipulating an object graph at the bean creation time or run time. It is similar to other expression languages like JSP EL, OGNL, MVEL and JBoss EL etc with some additional features like method invocation and basic string templating functionality.

Spring SpEL Regex:

Spring SpEL provides the facility to support regular expressions using keyword “matches“.

Syntax:

#{‘value’ matches ‘regex’ }

Example:

RegexTest.java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
@Component("regexTestBean")
public class RegexTest {
    // Check if this is a digit or not?
	@Value("#{'250' matches '\\d+' }")
	private boolean validDigit;
 
	public boolean isValidDigit() {
		return validDigit;
	}
 
	public void setValidDigit(boolean validDigit) {
		this.validDigit = validDigit;
	}
 
}

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
 <context:component-scan base-package="com.javawithease.business" />
 
</beans>

Test.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
/**
 * Spring SPEL Regex example.
 * @author javawithease
 */
public class Test {
 public static void main(String args[]){	
  //Get application context object.
  ApplicationContext context = 
	new ClassPathXmlApplicationContext("applicationContext.xml");
 
  //Get regexTestBean.
  RegexTest regexTest = (RegexTest) context.getBean("regexTestBean");
 
  //Test data.
  System.out.println("Is valid: "+regexTest.isValidDigit()); 
 }
}

Output:

Is valid: true

 
Download this example.