Spring Literal Expressions Example

0

In this article, we demonstrate the usage of spring expression language in evaluating basic literals.

The types of literal expressions supported are:

  1. string
  2. boolean
  3. integer
  4. hex integer
  5. long
  6. float
  7. double
  8. exponential
  9. Date
  10. null

This example uses the following frameworks:

  1. Maven 3.2.3
  2. Spring 4.1.5.RELEASE
  3. Eclipse  as the IDE, version Luna 4.4.1.

Dependencies

Add the following dependencies:

  1. spring-core
  2. spring-context
  3. spring-beans

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javarticles.spring</groupId>
	<artifactId>springListExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
	</dependencies>

	<properties>
		<spring.version>3.2.3.RELEASE</spring.version>
	</properties>

</project>

String Literal Expressions

You can inject simple string value direct as the value of @Value annotation. If you want to invoke some function on string, the string must be delimited by single quotes and then call the method on the delimited string. Since it is an expression and not just a value, it must be within #{<spring expression>}. To put a single quote itself in a string use two single quote characters.

StringBean:

package com.javarticles.spring;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class StringBean {

    @Value("John")
    private String name;
    
    @Value("#{'Hello World'.substring(6)}")
    private String substringValue;

    public String getName() {
        return name;
    }

    public String getSubstringValue() {
        return substringValue;
    }
}

StringLiteralExpressionExample:

package com.javarticles.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class StringLiteralExpressionExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            StringBean stringBean = (StringBean) context.getBean("stringBean");
            System.out.println("name=" + stringBean.getName());            
            System.out.println("'Hello World'.substring(6)=" + stringBean.getSubstringValue());
        } finally {
            context.close();
        }
    }
}

Output:

name=John
'Hello World'.substring(6)=World

Boolean Literal Expressions

You can use ‘true'(or ‘false’), ‘1’ (or ‘0’) or ‘yes’ (or ‘no’) as the boolean expessions and it will be evaluate to a boolean value.

BooleanBean:

package com.javarticles.spring;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class BooleanBean {

    @Value("true")
    private boolean booleanTrueValue;
    
    @Value("1")
    private boolean oneValue;
    
    @Value("yes")
    private boolean yesValue;

    public boolean isBooleanValueTrue() {
        return booleanTrueValue;
    }   
    
    public boolean isOneTrue() {
        return oneValue;
    }
    
    public boolean isYesTrue() {
        return yesValue;
    }
}

BooleanLiteralsExpressionExample:

package com.javarticles.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BooleanLiteralsExpressionExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            BooleanBean booleanBean = (BooleanBean) context.getBean("booleanBean");

            System.out.println("Boolean ('1')=" + booleanBean.isOneTrue());
 
            System.out.println("Boolean ('true')=" + booleanBean.isBooleanValueTrue());
            
            System.out.println("Boolean ('yes')=" + booleanBean.isYesTrue()); 
        } finally {
            context.close();
        }
    }
}

Output:

Boolean ('1')=true
Boolean ('true')=true
Boolean ('yes')=true

Number Literals Expressions

We can use numeric string expressions to evaluate to float, int, double values.
You can construct a new integer, for example, #{new Integer(20)}.
You can multiple numeric values, for example, #{2.5d * 2}.

NumberBean:

package com.javarticles.spring;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class NumberBean {
    @Value("5000")
    private int intValue;
    
    @Value("2.5")
    private Double doubleValue;
    
    @Value("#{2.5d}")
    private Double doubleValueExpression;
    
    @Value("3.2")
    private float floatValue;    
    
    @Value("#{new Integer(20)}")
    private Integer newInt;
    
    @Value("-2.5d")
    private Double negativeDoubleValue;
    
    @Value("#{2.5d * 2}")
    private Double multiplyDoubleValue;
    
    public int getIntValue() {
        return intValue;
    }

    public Double getDoubleValue() {
        return doubleValue;
    }

    public Double getDoubleValueExpression() {
        return doubleValueExpression;
    }

    public float getFloatValue() {
        return floatValue;
    }

    public Integer getNewInt() {
        return newInt;
    }

    public Double getNegativeDoubleValue() {
        return negativeDoubleValue;
    }

    public Double getMultiplyDoubleValue() {
        return multiplyDoubleValue;
    }         
}

NumberLiteralsExpressionExample:

package com.javarticles.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class NumberLiteralsExpressionExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            NumberBean numberBean = (NumberBean) context.getBean("numberBean");

            System.out.println("Float=" + numberBean.getFloatValue());
 
            System.out.println("Integer=" + numberBean.getIntValue()); 
                        
            System.out.println("Double=" + numberBean.getDoubleValue());
            
            System.out.println("Double expression '2.5d'=" + numberBean.getDoubleValueExpression());
            
            System.out.println("Double negative value=" + numberBean.getNegativeDoubleValue());
                        
            System.out.println("new Integer(20)=" + numberBean.getNewInt());
            
            System.out.println("(2.5d * 2)=" + numberBean.getMultiplyDoubleValue());
        } finally {
            context.close();
        }
    }
}

Output:

Float=3.2
Integer=5000
Double=2.5
Double expression '2.5d'=2.5
Double negative value=-2.5
new Integer(20)=20
(2.5d * 2)=5.0

Hexadecimal Expressions

You can also evaluate hexadecimal expressions, for example, #{0x35 * 3L}.

HexBean:

package com.javarticles.spring;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class HexBean {

    @Value("0x7FFFF")
    private int hexIntValue;

    @Value("0x4AFFF")
    private Long hexLongValue;
    
    @Value("#{0x35 * 3L}")
    private Long hexExpression;
    
    @Value("#{-0x20L}")
    private Long hexNegativeLongValue;    

    public int getHexIntValue() {
        return hexIntValue;
    }

    public Long getHexLongValue() {
        return hexLongValue;
    }

    public Long getHexExpression() {
        return hexExpression;
    }

    public Long getHexNegativeLongValue() {
        return hexNegativeLongValue;
    }    
}

HexLiteralsExpressionExample:

package com.javarticles.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HexLiteralsExpressionExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            HexBean hexBean = (HexBean) context.getBean("hexBean");

            System.out.println("int 0x7FFFF=" + hexBean.getHexIntValue());
 
            System.out.println("0x35 * 3L=" + hexBean.getHexExpression()); 
                        
            System.out.println("-0x20L=" + hexBean.getHexNegativeLongValue());
            
            System.out.println("long 0x4AFFF=" + hexBean.getHexLongValue());
            
        } finally {
            context.close();
        }        
    }
}

Output:

int 0x7FFFF=524287
0x35 * 3L=159
-0x20L=-32
long 0x4AFFF=307199

Exponential Expressions

Here you will see exponential expressions, for example, 2.1E+1.

ExponentBean:

package com.javarticles.spring;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ExponentBean {

    @Value("2.1E-7")
    private Double exponentialValue;
    
    @Value("2.1E+1")
    private Double exponentialDoubleValue;

    public Double getExponentialValue() {
        return exponentialValue;
    }

    public Double getExponentialDoubleValue() {
        return exponentialDoubleValue;
    }
        
}

ExponentLiteralExpressionExample:

package com.javarticles.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ExponentLiteralExpressionExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            ExponentBean exponentBean = (ExponentBean) context.getBean("exponentBean");
            System.out.println("2.1E-7=" + exponentBean.getExponentialValue());
            System.out.println("2.1E+1=" + exponentBean.getExponentialDoubleValue());  
        } finally {
            context.close();
        }
    }
}

Output:

2.1E-7=2.1E-7
2.1E+1=21.0

Date Literal Expression

In this example, we inject a Date object using #{new java.text.SimpleDateFormat('yyyyMMdd').parse('20150616')} expression.

DateBean:

package com.javarticles.spring;

import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class DateBean {

    @Value("#{new java.text.SimpleDateFormat('yyyyMMdd').parse('20150616')}")
    private Date dateValue;

    public Date getDateValue() {
        return dateValue;
    }
    
}

DateLiteralsExpressionExample:

package com.javarticles.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DateLiteralsExpressionExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            DateBean dateBean = (DateBean) context.getBean("dateBean");
            System.out.println("new java.text.SimpleDateFormat('yyyyMMdd').parse('20150616')=" + dateBean.getDateValue());
        } finally {
            context.close();
        }
    }
}

Output:

new java.text.SimpleDateFormat('yyyyMMdd').parse('20150616')=Tue Jun 16 00:00:00 IST 2015

Null value Expression

To inject a null value, use expression #{null}. If you just pass “null”, it will be evaluated to string ‘null’.

NullVariableBean:

package com.javarticles.spring;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class NullVariableBean {
    
    @Value("#{null}")
    private String nullValue;
    
    @Value("null")
    private String nullStringValue;

    public String getNullValue() {
        return "Is value '#{null}' null? " + (nullValue == null);
    }

    public String getNullStringValue() {
        return "Is value 'null' null? " + (nullStringValue == null);
    }    
}

NullLiteralExpressionExample:

package com.javarticles.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class NullLiteralExpressionExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            NullVariableBean nullVariableBean = (NullVariableBean) context.getBean("nullVariableBean");

            System.out.println(nullVariableBean.getNullStringValue());
 
            System.out.println(nullVariableBean.getNullValue());                      
            
        } finally {
            context.close();
        }
    }
}

Output:

Is value 'null' null? false
Is value '#{null}' null? true

Download the source code

This was an example about spring literal expressions.

You can download the source code here: springLiteralExpressionsExample.zip
Share.

Comments are closed.