Java如何使用Spring EL进行数学运算?
我们知道,在SpringEL中可以表示的最简单的值是文字值,例如number。此外,我们还可以使用SpringEL进行数学运算。下面的spring配置向您展示了如何使用SpringExpressionLanguage进行数学运算。这些操作包括:
加法运算(+)
减法运算(-)
乘法运算(*)
除法运算(/)
模运算(%)
幂运算(^)
<?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="myBean"> <property name="total" value="#{50 + 50}"/> <property name="length" value="#{100 - 10}"/> <property name="size" value="#{10 * 10}"/> <property name="reminder" value="#{10 % 3}"/> <property name="distance" value="#{1000 / 10}"/> <property name="power" value="#{2 ^ 10}"/> </bean> </beans>
上面的配置需要一个名为MyBean的bean/pojo。这是一个简单的类,其中包含一些字段以及getter和setter。随后是一个名为SpELMathOperationDemo的简单类,用于演示SpringEL数学运算。
package org.nhooo.example.spring.el; public class MyBean { private int total; private int length; private int size; private float distance; private int reminder; private int power; public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public float getDistance() { return distance; } public void setDistance(float distance) { this.distance = distance; } public int getReminder() { return reminder; } public void setReminder(int reminder) { this.reminder = reminder; } public int getPower() { return power; } public void setPower(int power) { this.power = power; } }
package org.nhooo.example.spring.el; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpELMathOperationDemo { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spel-math-operation.xml"); MyBean bean = (MyBean) context.getBean("myBean"); System.out.println("bean.getTotal() = " + bean.getTotal()); System.out.println("bean.getLength() = " + bean.getLength()); System.out.println("bean.getSize() = " + bean.getSize()); System.out.println("bean.getReminder() = " + bean.getReminder()); System.out.println("bean.getDistance() = " + bean.getDistance()); System.out.println("bean.getPower() = " + bean.getPower()); } }
这是由代码片段打印出来的输出:
bean.getTotal() = 100 bean.getLength() = 90 bean.getSize() = 100 bean.getReminder() = 1 bean.getDistance() = 100.0 bean.getPower() = 1024