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="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.xsd">
<bean id="student" class="org.kodejava.spring.core.el.Student">
<property name="name" value="Alice" />
<property name="grade" value="#{grade.getName()?.toUpperCase()}" />
</bean>
<bean id="grade" class="org.kodejava.spring.core.el.Grade">
<property name="name">
<null />
</property>
<property name="description" value="A beginner grade." />
</bean>
</beans>
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.
Below is the demo program code:
package org.kodejava.spring.core.el;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpELNullSafeExpressionDemo {
public static void main(String[] args) {
try (ClassPathXmlApplicationContext 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:
Name = Alice
Grade = null
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.3.23</version>
</dependency>
</dependencies>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
This has literally blown my mind. Thank you for sharing.