How do I handle or avoid null value in Spring EL?

In this example you will learn how to avoid a null value, which causing a NullPointerException thrown in a Spring EL expression. To avoid this from happening we can use the null-safe accessor, using the ?. operator.

We are using the previous example, How do I inject bean’s property using Spring EL? classes, which are the Student class and the Grade class. What we need is to create a new spring configuration file to demonstrate this feature. So, here is the configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    <bean id="student" class="org.kodejava.example.spring.model.Student">
        <property name="name" value="Alice"/>
        <property name="grade" value="#{grade.getName()?.toUpperCase()}"/>
    <bean id="grade" class="org.kodejava.example.spring.model.Grade">
        <property name="name">
        <property name="description" value="A beginner grade."/>

The use of null-safe accessor can be seen on the student bean’s grade property. We are calling the grade.getName() method and convert it to uppercase. We deliberately set the property to null. Calling toUpperCase on a null value will throw the NullPointerException. But because we are using the null-safe accessor the exception is not thrown, because the expression will not execute the code after the null-safe accessor. In this case when getName() return null, the toUpperCase() method will never get called.

Below is the demo program code:

package org.kodejava.example.spring.spel;

import org.kodejava.example.spring.model.Student;
import org.springframework.context.ApplicationContext;

public class SpELNullSafeExpressionDemo {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spel-null-safe.xml");

        Student student = (Student) context.getBean("student");
        System.out.println("Name  = " + student.getName());
        System.out.println("Grade = " + student.getGrade());

Here is the result of the code:

Feb 17, 2014 1:56:46 PM prepareRefresh
INFO: Refreshing[email protected]: startup date [Mon Feb 17 13:56:46 CIT 2014]; root of context hierarchy
Feb 17, 2014 1:56:46 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spel-null-safe.xml]
Name  = Alice
Grade = null
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.
Wayan Saryada

Leave a Reply