Search code examples
xmlspringspring-el

How to write nested SpEL expression in XML


I am trying to use SpEL expression like below but not working.

<intercept-url pattern="/myurl" 
     access="#{'${perm.status}' == 'secured' ? 'T(XXX.YYY.PermissionsConstants).PERMISSION_NAME' : 
            'IS_AUTHENTICATED_ANONYMOUSLY'}"/>  

If I replace T(XXX.YYY.PermissionsConstants).PERMISSION_NAME with constant like VIEW_PERM then it is working. Everything else is working fine except constant part. I tried with #{T(XXX.YYY.PermissionsConstants).PERMISSION_NAME} also but no luck.

Please suggest me correct syntax.


Solution

  • You should write SpEL like #{expression}.

    In your case it should be like

    <intercept-url pattern="/myurl" 
         access="#{'${perm.status}' == 'secured' ? T(XXX.YYY.PermissionsConstants).PERMISSION_NAME : 
                'IS_AUTHENTICATED_ANONYMOUSLY'}"/>  
    

    Don't wrap T(XXX.YYY.PermissionsConstants).PERMISSION_NAME with quotes, while '${perm.status}' or any String needs to be wrapped with quotes.

    Suppose that you need to write the same expression in java class then you would be writing it like:

    @Value("${perm.status}")
    String permStatus;
    
    // Inside a method
    String expressionValue =  == permStatus == "secured" ? PermissionsConstants.PERMISSION_NAME : "IS_AUTHENTICATED_ANONYMOUSLY";
    
    

    Similarly, you need to write it inside #{} with some changes:

    1. Replace double quotes with single quotes

    2. Class name should be replaced with fully qualified class name

    3. Wrap fully qualified class name with T() before accessing any constant from the class.

    Hope this helps!