Using @Value with SpEL - Value Injection Based on Configuration File or Non-Configured File - Spring Boot

This article mainly introduces the analysis of the method of using Spring @Value annotation to inject attribute values. The article introduces the sample code in great detail. It has a certain reference learning value for everyone's study or work.

In projects using the spring framework, @Value is one of the frequently used annotations. Its function is to assign values ​​corresponding to keys in the configuration file to its annotated properties. In daily use, our commonly used functions are relatively simple. This article gives you a systematic understanding of the usage of @Value.

@Value injection form

According to the source of the injected content, the @Value property injection function can be divided into two types: property injection through configuration files and property injection through non-configuration files.

The types of non-profile injections are as follows:

  • Inject plain string
  • Inject operating system properties
  • Injection expression results
  • Inject other bean properties
  • Inject file resources
  • Inject URL resource

Profile based injection

First, let's take a look at data injection in a configuration file, whether it's the default loaded application.properties or a custom my.properties document (which requires @PropertySource to be additionally loaded). For example: the application.properties property value is defined in the following form:

user.name=admin

The properties defined in the my.properties configuration file are as follows:

user.password=pwd123

Then, use @Value in the bean like this:

@PropertySource("classpath:my.properties")
@RestController
public class ValueController {

  /**
   *Get in application.properties Properties configured in
   */
  @Value("${user.name}")
  private String name;

  /**
   *Get in my.properties Configuration properties in
   */
  @Value("${user.password}")
  private String password;

}

The difference is that in a spring boot project, if you use the my.properties file, you need to import the configuration file through @PropertySource in the class, and the properties in application.properties will be loaded automatically.

At the same time, you can not only inject individual properties via @Value, but also in the form of arrays and lists. For example, the configuration is as follows:

tools=car,train,airplane

It can be injected by:

/**
 *Injection array (automatically split according to ",")
 */
@Value("${tools}")
private String[] toolArray;

/**
 *Injection list form (automatic segmentation based on "," and)
 */
@Value("${tools}")
private List<String> toolList;

By default, spring will split by "," and convert it to the corresponding array or list.

Non-profile based injection

Let's take a look at SpEl before using an example to illustrate a non-profile injected property based instance.

Spring Expression Language is the Spring Expression Language that can query and manipulate data at runtime. Using #{…} as an operator, all characters in curly braces are treated as SpEl.

Let's look at the application of a specific example scenario:

/**
 *Instantiate a string with default values
 */
@Value
private String wechatSubscription;

/**
 *Read system environment variables
 */
@Value("#{systemProperties['os.name']}")
private String systemPropertiesName;

/**
 *Inject expression evaluation result
 */
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private double randomNumber;

/**
 *Read the tool property of a bean:config and inject it
 */
@Value("#{config.tool}")
private String tool;

/**
 *Separate words as a string array with "|"
 */
@Value("#{'${words}'.split('\|')}")
private List<String> numList;

/**
 *Inject a file resource
 */
@Value("classpath:config.xml")
private Resource resourceFile;

/**
 *Inject URL resource
 */
@Value("http://www.choupangxia.com")
private URL homePage;

The above example shows the use of the following scenarios:

  1. Injecting a string directly is equivalent to initializing the string directly at instantiation. initialize empty string
  2. Inject system variables via #{}.
  3. Expression evaluation results are injected via #{}.
  4. Inject properties of other bean s via #{}.
  5. Properties are injected via a combination of {} and ${}, then split.
  6. Inject file resources and convert corresponding string values ​​to corresponding resource files.
  7. Inject URL resources and convert corresponding URL strings to URLs.

Default value injection

Whether you use #{}(SpEL) or ${} for property injection, when the corresponding value cannot be obtained, you need to set a default value, which can be set in the following ways.

/**
 *If IP is not configured in the property, the default value is used
 */
@Value("${ip:127.0.0.1}")
private String ip;

/**
 *If the value of port is not obtained in the system properties, 8888 is used.
 */
@Value("#{systemProperties['port']?:'8888'}")
private String port;

Use ":" directly in ${} to set default value of undefined or empty value, while #{} requires "?:" to set default value of unset property.

Welcome to pay attention to my blog, there are many fine collections in it

  • This article is reproduced to indicate the source (must be linked, not just text): Antetokounmpo Blog .

If you find it helpful, please like and share! Your support is my inexhaustible creative motivation! . In addition, the author has recently output the following fine content, looking forward to your attention.

Tags: Spring

Posted by Zoxive on Tue, 31 May 2022 04:58:52 +0530