SoFunction
Updated on 2025-03-03

Detailed explanation of how to set default values ​​for @Value annotation in Spring

How to set default values ​​for @Value annotation in Spring

In Spring development, we often encounter situations where we need to read attributes from configuration files. @Value annotation is a convenient way provided by Spring, which allows us to easily inject properties from configuration files into Spring Beans. However, in some scenarios, a certain attribute may not be defined in the configuration file, or the attribute value cannot be obtained for other reasons. To ensure the robustness of the program, we usually want to set a default value for the property in this case.

1. Understand @Value annotation

The @Value annotation is one of the commonly used annotations for property injection in Spring. It is able to inject property values ​​from external configurations (such as or) into Spring's beans. For example:

@Value("${}")
private String appName;

In the above code, the value of the appName field will be injected into the corresponding property value in the file. If no attribute is found in the configuration file, Spring will throw an IllegalArgumentException exception, which is often not the result we want.

2. Why do you need a default value?

In actual development, the following situations may be encountered:

  1. Properties in configuration files may be forgotten: The developer may forget to define a property in the configuration file. If there is no logic in the program to handle this situation, the application startup will fail.
  2. Flexibility requirements: Certain properties may be optional. In this case, we want to use a reasonable default value when the property is not configured.
  3. Environmental differences: Different environments (such as development, testing, production) may have different configuration requirements. In some environments, certain properties may not require configuration.

To deal with these situations, we usually need to@ValueAnnotations provide a default value.

3. How to set the default value for @Value?

for@ValueSetting the default value is very simple. You just need to add a colon after the attribute name:, and keep up with the default value.

@Value("${:100}")
private Integer totalBaseNum;

The above code means that if there is no definition in the configuration file,SototalBaseNumThe default value will be100. The following is the specific usage analysis:

  • ${}: This is the placeholder syntax for getting from the configuration filevalue.
  • :100: means that it cannot be obtainedThe default value used when the attribute is100

4. Default value settings for different data types

Spring supports attribute injection for multiple data types, and for each type, the default value can be set. Here are some common data types and their default value settings:

  • String type

@Value("${:DefaultAppName}")
private String appName;
  • If the configuration file is not defined,SoappNameWill be assigned as"DefaultAppName"

  • Integer Type

@Value("${:10}")
private Integer maxConnections;
  • If the configuration file is not defined,SomaxConnectionsWill be assigned as10

  • Boolean type

@Value("${:false}")
private Boolean featureEnabled;
  • If the configuration file is not defined,SofeatureEnabledWill be assigned asfalse

  • Floating point type

@Value("${:0.5}")
private Double thresholdValue;
  • If the configuration file is not defined,SothresholdValueWill be assigned as0.5

  • List Type

    For list type values, you can use comma-separated form to define the default value.

@Value("${servers:server1,server2,server3}")
private List<String> servers;
  • If the configuration file is not definedservers,SoserversThe list will contain"server1""server2""server3"

5. Practical application scenarios using default values

In actual development, there are many scenarios where default values ​​are set. Here are some common application scenarios:

  • Database connection pool settings

    When setting up a database connection pool, you may want to set a default value for the maximum number of connections:

@Value("${:20}")
private Integer maxConnections;
  • This ensures that even if the developer forgets to configure the property, the app is still able to run with the default value of 20 connections.

  • Feature switch

    Some application features may require configuration files to control enablement or disabling. You can do this using the default values ​​of the boolean type:

@Value("${:false}")
private Boolean isFeatureEnabled;
  • This ensures that the feature is turned off by default when the switch is not set in the configuration file.

  • API timeout settings

    When calling an external API, timeout is usually an important configuration item. You can set a reasonable default value for the timeout:

@Value("${:5000}")
private Integer apiTimeout;
  • This way, if the timeout time is not set in the configuration file, the API call will time out after 5 seconds by default.

  • Log level control

    You can set a default value for the log level to ensure that the logs can still be output at a default level when not set in the configuration file:

@Value("${:INFO}")
private String loggingLevel;
  • This ensures that the application can still use the configuration file without the configuration fileINFOLevel output log.

6. Common traps and precautions

Although@ValueIt is very simple to set the default value of annotations, but there are still some common pitfalls and precautions to pay attention to in actual use:

Default value format matches type

The default value format must match the type of the injected property. For example, if you want to inject oneIntegerFor attributes of type, then you should make sure that the default value is a valid integer. Otherwise, it will causeNumberFormatExceptionabnormal.

@Value("${:notAnInteger}")
private Integer someValue;  // This will cause an exception

Processing of empty strings

In some cases, you may want the default value to be an empty string. You can use""As the default value:

@Value("${:}")
private String someKey;
  • In this way, when the configuration file is not definedhour,someKeyWill be assigned an empty string.

Using SpEL expressions

If your default values ​​require more complex logic processing, you can use Spring Expression Language (SpEL) to implement it. For example, use SpEL to set default values ​​based on conditions:

@Value("#{${} ?: 'defaultValue'}")
private String someKey;

This code means that if it does not exist, someKey will be assigned a value of "defaultValue".

Multi-environment configuration

When you have multiple environments (such as development, testing, production), different default values ​​may be set for each environment. You can use the application-{profile}.properties file to set different default values ​​for different environments. For example, set the default value of a development environment in the setting and the default value of a production environment in the setting.

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

In a development environment, it can be set to 8081, and in a production environment, it can be set to 80.

The hierarchy of attributes

In Spring, properties are inheritable, which means you can define default values ​​in higher-level configuration files and then override those default values ​​in lower-level configuration files. For example, you can define global default values ​​in it and then override those default values ​​in it for the development environment.

# 
=5000

# 
=3000

In this way, in the development environment,The value will be 3000, and in other environments it will be 5000.

7. Summary

Setting default values ​​for @Value annotations is a common and practical trick in Spring development. It not only enhances the robustness of the program, but also provides flexible configuration management for different environments. In actual applications, developers should use the default values ​​reasonably according to project requirements to avoid program exceptions caused by missing configuration.

By understanding and mastering these techniques, you can handle various configuration requirements more calmly in Spring development, while improving program stability and maintainability.

The above is a detailed explanation of how to set default values ​​for @Value annotation in Spring. For more information about setting default values ​​for Spring for @Value, please follow my other related articles!