SoFunction
Updated on 2025-03-09

Set default values ​​to @Value and assign values ​​to static variables

@Value Usage

1. No default value is specified when assigning

@Value("${}")
private int serverPort;

The corresponding configuration file is as follows

=8080

As mentioned above, when the program starts, the attribute value corresponding to the configuration file will be automatically assigned to the corresponding variable

Note:

  • Without specifying a default value,
  • If you forget to configure the corresponding properties in the configuration file,
  • An error will be reported when the program starts, causing the program to fail to start.
  • This situation can specify a default value for @Value to avoid this problem

2. Specify the default value when assigning

@Value("${:8080}")
private int serverPort;

As above, if there is no corresponding attribute configured in the configuration file, 8080 is used as the default value

3. Assign values ​​to static variables

In some specific situations, you need to assign a value to a static variable. @Value cannot be used directly on a static variable, so that the configuration value cannot be injected into the static variable

You can use the Set method to assign values ​​to static variables

private static int serverPort;
@Value("${}")
public void setServerPort(Integer serverPort) {
	Class Name.serverPort = serverPort;
}

Note:

  • The above methods can also specify the default value

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.