Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a constant in Spring Expression Language

i am quite new to Spring and i have a bean declaration as follows.

    <bean id="mybean" class="" scope="prototype">
       <property name='typeOf' value='#{typeOfBuilder.getKeyFor("OPEN_DATE").getId()}'/>    
</bean> 

typeOf is a type of Integer which is the key of another table which typeOfBuilder builds by Key which is OPEN_DATE in this case.

this code works OK but have a limitation. OPEN_DATE is a constant in a NON-MANAGE Spring Bean something like follows.

public final class Constants
{
     public final static String KEY_FOR_OPEN_DATE = "OPEN_DATE";     
} 

and is strongly recommend to be able to reference to it!!.

something like this.

<util:constant id="PATH_TO_CONSTANT" static-field="myPath"/>
<property name='typeOf' value='#{typeOfBuilder.getKeyFor(PATH_TO_CONSTANT).getId()}'/>  

any help is hugely appreciate.

like image 269
chiperortiz Avatar asked Jul 22 '14 13:07

chiperortiz


People also ask

What is the spring expression language?

The Spring Expression Language (SpEL for short) is a powerful expression language that supports querying and manipulating an object graph at runtime.

How to access class-scoped methods or constants using spring expression language?

In this examples you will learn how to access class-scoped methods or constants using Spring Expression Language. To access a class-scoped methods or constants you will need to use the T () operator of the Spring EL, for example T (java.lang.Math). This operator will give us the access to static methods and constants on a given class.

What is the constant expression language?

The Constant Expression Language is really just a way to use a constant value or object. This is a fixed constant value (or object) that is only set once during starting up the route, do not use this if you want dynamic values during routing. The Constant language supports 2 options, which are listed below. Sets the class name of the constant type.

How to access a static method in spring El?

As an example we can access the Math.PI in Spring EL like T (java.lang.Math).PI. Just like accessing the static constants we can also access a static method in the same way. For example we can call the Math.random () method in Spring EL like this T (java.lang.Math).random (). Now let’s see how we do these inside a spring configuration file.


1 Answers

The special 'T' operator can be used to specify an instance of java.lang.Class (the 'type'). Static methods are invoked using this operator as well.

Try the code below.

<property name='typeOf' value='#{typeOfBuilder.getKeyFor(T(some.package.Constants).KEY_FOR_OPEN_DATE).getId()}'/>
like image 97
pgiecek Avatar answered Sep 24 '22 12:09

pgiecek