JVM Languages

Tools

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:

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 grade.name 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.