Home  >  Spring Core

Safe Navigation Operator in Spring Expression Language (SpEL)

By Arvind Rai, October 26, 2013
Spring expression language (SpEL) provides safe navigation operator to avoid null pointer expression. In the below example we have a string that length will be called. The method length will be called on null also and it will not throw exception. For our example we are using spring version 3.2.2.RELEASE.

SpELTest.java
package com.concretepage;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import com.concretepage.bean.Student;
public class SpELTest {
	public static void main(String[] args) {
		ExpressionParser parser = new SpelExpressionParser();
		Student std = new Student();
		std.setName("Ram");
		StandardEvaluationContext context = new StandardEvaluationContext(std);
		String name = parser.parseExpression("Name?.length()").getValue(context, String.class);
		System.out.println(name);
		std.setName(null);
        name = parser.parseExpression("Name?.length()").getValue(context, String.class);
		System.out.println(name);
	}
}
 


Student.java
package com.concretepage.bean;
public class Student {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}
Output
3
null
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us