Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How concatenate two string in Spring Expression Language (SpEL)

In my spring application, the methods from my controller and service classes have this annotation to security purposes:

@PreAuthorize("hasPermission(#user, 'cadastra')")

the second argument, the permission, should have this format:

<<action_name>>_<<class_name>>

What expression I should use to accomplish that, taking in consideration the class name is held by this.getClass().getName()?

like image 286
Kleber Mota Avatar asked Jun 09 '14 13:06

Kleber Mota


People also ask

How do you concatenate 2 strings?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.

What is SpEL expression in spring?

The Spring Expression Language (SpEL for short) is a powerful expression language that supports querying and manipulating an object graph at runtime. The language syntax is similar to Unified EL but offers additional features, most notably method invocation and basic string templating functionality.

Which of the following can be used to fetch the value of a SpEL expression @SpEL?

Using ExpressionParser. ExpressionParser is responsible for parsing expression strings. In this example, SpEL parser will simply evaluate the string 'Any String' as an expression.


2 Answers

To concatenate two strings in Spring EL you use concat function . See here for more details : Spring EL docs

for example, I used the following :

    @PreAuthorize("hasRole('ROLE_'.concat(this.class.simpleName))")
like image 50
Louise Miller Avatar answered Oct 22 '22 19:10

Louise Miller


I finally solve this. I add a new method in my controller:

public String getName() {
    String nome_classe = entityClass.getSimpleName();
    System.out.println("getName nome_class = "+nome_classe);
    return nome_classe;
}

and now I use the annotation in that way:

@PreAuthorize("hasPermission(#user, 'cadastra_'+#this.this.name)")
like image 45
Kleber Mota Avatar answered Oct 22 '22 19:10

Kleber Mota