Ad Code

✨🎆 Diwali Dhamaka Offer! 🎆✨

Get 20% OFF on All Courses at Shiva Concept Solution click

SpEL in Spring Core

SPEL in Spring Core: 

It is Expression Language that provide Query and Manipulation using normal expression.

it is basically used into Object Graph and Inline Operation on Spring Application. it is not directly connected with XML configuration, it can be directly used by Spring Expression class and methods.

How to Use Spell:

1. Use ExpressionParser Class: create an instance of ExpressionParser to parse the SpEL expression.

2. Parse the Expression:

Use the parseExpression() method of the ExpressionParser to parse the SpEL expression string.

3. Provide an EvaluationContext:

An EvaluationContext provides the context in which the expression will be evaluated. It can be a StandardEvaluationContext or a custom implementation.


4. Evaluate the Expression:

Use the getValue() method of the Expression object to evaluate the expression and get the result. 


Example to concatenate String:


package com.scs.ExpressionLanguage;

import org.springframework.expression.Expression;

import org.springframework.expression.ExpressionParser;

import org.springframework.expression.spel.standard.SpelExpressionParser;

import org.springframework.expression.spel.support.StandardEvaluationContext;

public class ExpressionParserExample {


public static void main(String[] args) {

ExpressionParser parser = new SpelExpressionParser();

Expression exp = parser.parseExpression("'Hello' + 'Spel'");

String data = exp.getValue(String.class);

System.out.print(data);


}


}


Another Example of SpEL using Numeric Expression

package com.scs.ExpressionLanguage;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
public class ExpressionParserExample {

public static void main(String[] args) {
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("100 + 200");
String data = exp.getValue(String.class);
System.out.print(data);

}

}


Another Example of SpEL using Variable with Dynamic Input:

package com.scs.ExpressionLanguage;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
public class ExpressionParserExample {

public static void main(String[] args) {
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariable("a",1000);
context.setVariable("b",2000);
Expression exp= parser.parseExpression("#a + #b");
Integer data = exp.getValue(context,Integer.class);
System.out.print(data);

}

}



إرسال تعليق

0 تعليقات