In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to use SpringBoot SpringEL expressions", the content of the explanation is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn how to use SpringBoot SpringEL expressions!
1. Basic introduction of SpringEL-
What is SpringEL (SpEL)?
Spring expression language has been introduced into Spring3-SpringEL,SpEL is a powerful and concise way to assemble Bean.
SpringEL can assemble values into our properties or constructors through expressions executed at run time
SpringEL can call the static constant provided in JDK to get the configuration in the external Properties file
Why use SpringEL?
Bean usually injected through a configuration file or Annotaton can actually be called static injection.
For example, if there is a variable An in Bean A, its value needs to be referenced according to the B variable of Bean B. in this scenario, static injection is very powerless for this kind of processing.
The SpringEL added by Spring3 can fully meet this requirement, and the fields of different Bean can be calculated and assigned, so the function is very powerful.
How to use SpringEL?
SpringEL can see from the name that it has something to do with EL. The use of SpringEL is very similar to the use of EL expressions.
The EL expression is more convenient to get the value in the background in the JSP page, and SpringEL is to get the value of Bean in the Spring container more easily.
EL uses ${}, while SpringEL uses # {} for expression declaration
The main difference between the two
$is the parameter to find the external configuration and assign the value.
# is a SpEL expression to find the contents of the corresponding variable
You can also directly use @ value ("constant") injection without using EL, which is equivalent to direct assignment
If used in Spring, you can use * * @ PropertySource ("classpath:my.properties") * * to load the corresponding configuration file.
II. EL expression-basic use
# configuration file com: codecoord: el: num: 1001 name: el language:-java-spring-mysql-linux # Comma separated can be injected into the list language02: java,spring,mysql,linux
Use EL to inject simple values
/ * injecting simple values. Direct injection does not use EL,EL and does not support specifying constants directly * constants specified directly in EL will be treated as configuration, which is equivalent to direct assignment * / @ Value ("1432516744") private Integer no
Injection profile property value
/ * * injection integer attribute value * / @ Value ("${com.codecoord.el.num}") private Integer num;/** * injection character attribute value * / @ Value ("${com.codecoord.el.name}") private String name
Injection default
The default value is separated by a colon: * injection constant can actually specify a configuration that does not exist and then use the default value, where the value of skill is java * / @ Value ("${com.codecoord.el.skill:java}") private String skill.
Injection list
Array syntax format injection list in direct configuration file is not supported
Can recognize the use of commas, separated configuration, spring by default, separated by
/ / incorrect spelling: does not support direct injection of yml list format syntax list @ Value ("${com.codecoord.el.language}") private List listLanguage;@Value ("${com.codecoord.el.language}") private String [] strLanguage;/** * support, separated injection list * / @ Value ("${com.codecoord.el.language02}") private List listLanguage02;@Value ("${com.codecoord.el.language02}") private String [] strLanguage02
The complete reference is as follows
Configuration file
Server: port: 8888com: codecoord: el: num: 1001 name: el language:-java-spring-mysql-linux # Comma separated can be injected into the list language02: java,spring,mysql,linux
Property configuration class
Import lombok.Data;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;import java.util.List;@Data@Componentpublic class ElConfig {/ * injects simple values. Direct injection does not use EL,EL and does not support specifying constants directly * constants specified directly in EL will be treated as configuration, which is equivalent to direct assignment * / @ Value ("1432516744") private Integer no / * * injection integer attribute value * / @ Value ("${com.codecoord.el.num}") private Integer num; / * injection character attribute value * / @ Value ("${com.codecoord.el.name}") private String name The default value is separated by a colon: * injection constant can actually specify a configuration that does not exist and then use the default value, where the value of skill is java * / @ Value ("${com.codecoord.el.skill:java}") private String skill. / / No direct injection list / * @ Value ("${com.codecoord.el.language}") private List listLanguage; @ Value ("${com.codecoord.el.language}") private String [] strLanguage;*/ / * * supported, separated injection list * / @ Value ("${com.codecoord.el.language02}") private List listLanguage02 @ Value ("${com.codecoord.el.language02}") private String [] strLanguage02;}
The configuration class is injected into controller, and the test results of the access interface are as follows
{"no": 1432516744, "num": 1001, "name": "el", "skill": "java", "listLanguage02": ["java", "spring", "mysql", "linux"], "strLanguage02": ["java", "spring", "mysql", "linux"]} III. Basic use of SpringEL-
1. The simple value of SpEL injection is basically the same as that of ordinary EL injection.
2. SpEl is injected into map
The configuration file needs to be enclosed in double quotes, otherwise the injection will fail. Key is a single quote.
# SpElspEl: mapInject: "{" name ":" SpEl "," website ":" http://www.codeocord.com"}"
The java class first uses ${spEl.mapInject} to inject the string value, and # {} parses the string value to map
@ Value ("# {${spEl.mapInject}}") private Map mapInject
3. SpEl is injected into list
In addition to injecting listI through EL, you can also inject List using # {${} .split ("delimiter")}
Configuration files, for example, separated by #
SpEl: listInject: "4411, 99100"
The java class uses ${spEl.listInject} to inject string values, enclosing the contents in single quotation marks, and then using the split method to separate the strings
Tip: to avoid null, you can give a default value empty string
@ Value ("# {" ${spEl.listInject:} ".split (" # ")}") private List listInject
4. Dynamic injection
All of the above injections are static injections, and SpEl supports the injection of information from the Spring container, called dynamic injection. The dynamic injection classes are as follows
Import lombok.AllArgsConstructor;import lombok.Data;import org.springframework.stereotype.Component;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;@Component@Datapublic class SpElConstant {private String name = "SpElConstant-name"; private String nickname = "tianxin"; private int num = 100; private List product = new ArrayList () {{add ("huaweiMate30Pro"); add ("xiaomi10x5g");}} Private Map productMap = new HashMap () {{put ("huaweiMate30Pro", "5999"); put ("xiaomi10x5g", "4999");}}; private List cityList = new ArrayList () {{add (new City ("Shenzhen", 1000L)); add (new City ("Hangzhou", 2000L); add (new City ("Guiyang", 900L));}} Public String showProperty () {return "showProperty- has no parameters";} public String showProperty (String name) {return "showProperty-" + name;} @ Data @ AllArgsConstructor static class City {private String name; private long population;}}
SpEl supports and does not support operations
Support for dynamic injection of instances, similar to automatic object injection
SPL does not support direct injection of configurations in configuration files
Support for calling static and instance methods
Static method: @ Value ("# {T (package.ClassName) .ConstFieldName")
Support for calling static classes or constants
Support for operator operation
Support operation set
Support for query filtering collections and projections
The full injection operation is as follows
Import lombok.Data;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;import java.util.List;import java.util.Map;@Data@Componentpublic class SpElConfig {/ does not support direct injection profile value / * @ Value ("# {com.codecoord.el.num}") private Integer num;*/ / * object injection * / @ Value ("# {spElConstant}") private SpElConstant spElConstant / * inject ID into the STR constant / variable * / @ Value ("# {spElConstant.name}") private String name; / * call the no-parameter method * / @ Value ("# {spElConstant.showProperty ()}") private String method1 in spElConstant Bean / * the String returned by the method * / @ Value ("# {spElConstant.showProperty (" Hell SpringEL ")}") private String method2; / * is capitalized * / @ Value ("# {spElConstant.showProperty (). ToUpperCase ()}") private String method3 / * if you use method3, if showProperty returns null *, NullPointerException will be thrown. You can use the following ways to avoid * using?. The symbol means that if the value on the left is null, the right method * / @ Value ("# {spElConstant.showProperty ()? .toUpperCase ()}") private String method4; / * * injects the math constant * / @ Value ("# {T (UpperCase) .PI}") private double pi will not be executed. / * use the random method to get the return value * / @ Value ("# {T (java.lang.Math). Random ()}") private double random; / * get the file path symbol * / @ Value ("# {T (java.io.File) .comparator}") private String separator / * concatenation string * / @ Value ("# {spElConstant.nickname +"+ spElConstant.name}") private String concatString; / * operates on numeric types. SpElConstant has the num attribute * / @ Value ("# {3 * T (java.lang.Math). PI + spElConstant.num}") private double operation / * * perform logical operations * / @ Value ("# {spElConstant.num > 100 and spElConstant.num = 1000]}") private List cityList; / * * inject into cities with a population equal to 900 people * / @ Value ("# {spElConstant.cityList.? [population = = 1000]}") private SpElConstant.City city / * inject cities with a population greater than or equal to 1000, and retain only the city name * / @ Value ("# {spElConstant.cityList.? [population > = 1000].! [name]}") private List cityName;}
Injection result
{"spElConstant": {"name": "SpElConstant-name", "nickname": "tianxin", "num": 100," product ": [" huaweiMate30Pro "," xiaomi10x5g "]," productMap ": {" xiaomi10x5g ":" 4999 "," huaweiMate30Pro ":" 5999 "}," cityList ": [{" name ":" Shenzhen "," population ": 1000} {"name": "Hangzhou", "population": 2000}, {"name": "Guiyang", "population": 2000}}, "name": "SpElConstant-name", "method1": "showProperty- no parameter", "method2": "showProperty-Hell SpringEL", "method3": "SHOWPROPERTY- no parameter", "method4": "SHOWPROPERTY- no parameter", "pi": 3.141592653589793 "random": 0.19997238292235787, "separator": "," concatString ":" tianxin SpElConstant-name "," operation ": 109.42477796076938," logicOperation ": false," logicOperation2 ": true," logicOperation3 ": 200," str ":" huaweiMate30Pro "," upperStr ":" HUAWEIMATE30PRO "," mapValue ": null," mapStrByproduct ":" 5999 "," cityList ": [{" name ":" Shenzhen "," population ": 1000} {"name": "Hangzhou", "population": 2000}], "city": {"name": "Guiyang", "population": 2000}, "cityName": ["Shenzhen", "Hangzhou"]}
Spring manipulates external Properties files
Public class TestSpringEL {/ / Note that db is id @ Value ("# {db [" jdbc.url "]}") private String propertiesValue;} declared in the xml file.
SpringEL is only a string when used, it is not easy to debug and test, and there is no IDE to check our syntax. When errors occur, it is difficult to detect. Complex expressions are not recommended to be injected through SpringEL. When not necessary, complex injection of SpEl is not recommended. Clear and readable code is more important and facilitates troubleshooting.
IV. Automatic attribute injection
All of the above are injected through specified fields, and can be automatically injected with @ ConfigurationProperties specified prefix.
Org.springframework.boot.context.properties.ConfigurationProperties
Configuration class
User: id: ${random.uuid} name: autowire address: unknown website: www.codecoord.com age: ${random.int}
Automatic attribute injection class
Specify the front end as user through prefix, and then user. The latter type is injected by name
Note that the setter method must be provided
Import lombok.Data;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;@Component@ConfigurationProperties (prefix = "user") @ Datapublic class UserConfig {private String id; private String name; private String address; private String website; private Integer age;}
UserConfig can be forcibly injected again through @ EnableConfigurationProperties (value = UserConfig.class). The problem is that if UserConfig is a configuration class in a third-party jar package, the attribute may not be injected, so you can specify injection.
Thank you for your reading, the above is the content of "how to use SpringBoot SpringEL expressions". After the study of this article, I believe you have a deeper understanding of how to use SpringBoot SpringEL expressions, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.