Spring Boot integrated SpEL quick start demo
1. What ‘s SPEL?
Spring Expression Language (abbreviated SpEL) is a powerful expression language that supports querying and manipulating object graphs at runtime. The language syntax is similar to Unified EL, but provides additional features, most notably method calls and basic string template functionality.
SpEL Key Features:
- Literal expressions
- Boolean and relational operators
- regular expression
- Class expressions
- Visit properties, arrays, lists, maps
- Method calls
- Relational operators
- parameter
- Call the constructor
- Bean references
- Construct an Array
- Inline lists
- Inline maps
- Ternary operators
- variable
- User-defined functions
- Collection projection
- Collection filtering
- Template expressions
2. Code engineering
Objective: Implement attribute injection files, lis, and perform logical operations
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<parent>
<artifactId>springboot-demo</artifactId>
<groupId>com.et</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>SpEL</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
</dependencies>
</project>
bean
Read the property file and inject the expression into the list
@Value("#{'${server.name}'.split(',')}")
private List<String> servers;
Here are some common examples, for more you can go to the official website to see the detailed documentation, here is only a basic primer
package com.et.spel.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
@Component
public class BaseValueInject {
@Value("normal")
private String normal; // Inject ordinary string
@Value("#{systemProperties['os.name']}")
private String systemPropertiesName; //Inject operating system properties
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private double randomNumber; //Inject expression result
@Value("#{beanInject.another}")
private String fromAnotherBean; // Inject other Bean attributes: Inject the attribute another of the beanInject object. See the specific definition of the class below.
@Value("classpath:config.txt")
private Resource resourceFile; // Inject file resources
@Value("http://www.baidu.com")
private Resource testUrl; // Inject URL resources
@Override
public String toString() {
return "BaseValueInject{" +
"normal='" + normal + '\'' +
", systemPropertiesName='" + systemPropertiesName + '\'' +
", randomNumber=" + randomNumber +
", fromAnotherBean='" + fromAnotherBean + '\'' +
", resourceFile=" + resourceFile +
", testUrl=" + testUrl +
'}';
}
}
package com.et.spel.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class BeanInject {
@Value("another sss")
private String another;
public String getAnother() {
return another;
}
public void setAnother(String another) {
this.another = another;
}
}
application.yaml
server:
port: 8088
name: aaa,bbb,ccc
The above are just some of the key codes, all of which can be found in the repositories below
Code repositories
3. Testing
package com.et.spel;
import com.et.spel.controller.BaseValueInject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class DemoTests {
private Logger log = LoggerFactory.getLogger(getClass());
@Before
public void before() {
log.info("init some data");
}
@After
public void after() {
log.info("clean some data");
}
@Test
public void execute() {
log.info("your method test Code");
}
@Test
public void stringSpel() {
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World'");
String message = (String) exp.getValue();
log.info(message);
}
@Test
public void stringSpelConcat() {
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World'.concat('!')");
String message = (String) exp.getValue();
log.info(message);
}
@Autowired
private BaseValueInject baseValueInject;
@Test
public void baseValueInject() {
System.out.println(baseValueInject.toString());
}
}
Run the test class, return
2024-05-22 21:00:51.081 INFO 1868 --- [ main] com.et.spel.DemoTests : init some data
BaseValueInject{normal='normal', systemPropertiesName='Mac OS X', randomNumber=7.041399882847799, fromAnotherBean='another sss', resourceFile=class path resource [config.txt], testUrl=URL [http://www.baidu.com]}
2024-05-22 21:00:51.085 INFO 1868 --- [ main] com.et.spel.DemoTests : clean some data