在此示例中,您将学习如何避免null值,该值会导致NullPointerExceptionSpring EL表达式中引发。为了避免这种情况的发生,我们可以通过?.运算符使用null安全访问器。
我们正在使用前面的示例,如何使用Spring EL注入bean的属性?类,即Student类和Grade类。我们需要创建一个新的spring配置文件来演示此功能。因此,这是配置文件:<?xml version="1.0" encoding="UTF-8"?>
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">
在studentbean的grade属性上可以看到使用null安全访问器。我们正在调用该grade.getName()方法并将其转换为大写。我们特意将grade.name属性设置为null。调用toUpperCase一个null值都将抛出的NullPointerException。但是因为我们使用的是null安全访问器,所以不会引发异常,因为该表达式不会在null安全访问器之后执行代码。在这种情况下,当getName()return时null,该toUpperCase()方法将永远不会被调用。
下面是演示程序代码:package org.nhooo.example.spring.el;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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());
}
}
这是代码的结果:Name = Alice
Grade = null