Spring Boot - Inject Data Size Property

This tutorial shows you how to define data size values in Spring application properties that can be automatically converted to DataSize type.

In a Spring Boot application, data size can be represented as a DataUnit variable. Compared to storing the size in a numeric variable, it has some advantages such as the ease of converting to other size units. Common usages of that data type is for specifying a size limit. If your Spring Boot application needs to have configurable values that represent a data size, you can put the values in the application properties. It would be more convenient if the application properties values can be converted to the DataSize type. Fortunately, Spring has the ability to convert values in specific formats to be injected as DataSize variables. Below are the examples.

Inject DataSize Value

Specifying Size Unit

In the application properties, you can define a value by specifying the number followed by the size unit. The supported units are:

  • B: bytes
  • KB: kilobytes
  • MB: megabytes
  • GB: gigabytes
  • TB: terabytes

The size units must be written in upper case and it's allowed to add spaces between the number and the size unit. Keep in mind that Spring uses the traditional conversion where 1KB = 1024 bytes. In other words, we can say that Spring actually uses kibibyte, mebibyte gibibyte, and tebibyte.



If the format is correct, Spring will be able to convert to a DataSize object.

  private DataSize uploadLimit; // 102400B

  private DataSize downloadLimit; // 5242880B

@DataSizeUnit Annotation

Another alternative is by using @DataSizeUnit annotation. You don't need to specify the unit in the application properties. By default, Spring uses bytes as the default unit. If you want to use a different size unit, add a @DataSizeUnit annotation on the injected variable and specify the DataUnit to use. This annotation will be ignored if the value already has a size unit.



The two properties above do not have a size unit. For the imageLimit field below, since it's not annotated with the @DataSizeUnit annotation, the size unit will be set as bytes. Meanwhile, the property value for the attachmentLimit field below will be set to megabytes because of the annotation.

  private DataSize imageLimit; // 2000000B

  private DataSize attachmentLimit; // 3145728B

Add Default Value

Just like other property types, it's also possible to specify a default value after the property name, separated by :.

  private DataSize downloadLimit1; // 10MB

  private DataSize downloadLimit2; // 10 bytes

  private DataSize downloadLimit3; // 10KB


We have learned that Spring can convert values with certain formats to DataSize variables. To define data size values in the application properties , you can either specify the size unit or use @DataSize annotation. If you don't specify the unit and don't add the annotation, Spring will use bytes as the default unit.

You can also read about: