[JAVA] Sample code to assign a value in a property file to a field of the expected type

Overview

This is sample code to assign the value of the property file using the @Value annotation. The same result can be obtained with the Configuration class using the @ConfigurationProperties annotation, which is not covered in this article.

environment

reference

Array format value to List type

Substitute a numeric type array

I'm not sure if comma-separated values are called arrays in the properties file, but Spring Boot allows you to assign comma-separated values to collection-type fields.

Property file

properites


hoge.fuga = 100, 200, 300

Alternatively, it can be defined as an array by adding a subscript to the property name, such as [0].

properties


hoge.fuga[0]= 100
hoge.fuga[1]= 200
hoge.fuga[2]= 300

In the yml format, define by prefixing the value with -.

yml


hoge:
  fuga:
    - 100
    - 200
    - 300

code

@Value("${hoge.fuga}")
private List<Integer> fuga;

Substitute a string type array

Property file

properites


hoge.fuga =Apple,Mandarin orange,None

yml


hoge:
  fuga:
    -Apple
    -Mandarin orange
    -None

code

@Value("${hoge.fuga}")
private List<String> fuga;

Array format value to Set type

Substitute a string type array

Property file

properties


hoge.fuga =Apple,Mandarin orange,None

For yml files, you cannot assign an array to a Set field. If you try to assign an array like the one below, an exception will be thrown.

yml


hoge:
  fuga:
    -Apple
    -Mandarin orange
    -None

However, as with the properties file, you can substitute them if they are separated by commas.

yml


hoge:
  fuga:Apple,Mandarin orange,None

code

Value("${hoge.fuga}")
private Set<String> fuga;

Key / value format value to Map type

Assign to Map where key is string type

Property file

properites


hoge.fuga.key1 = val1
hoge.fuga.key2 = val2

yml


hoge:
  fuga:
    key1: val1
    key2: val2

code

@Value("${hoge.fuga}")
private Map<String, String> fuga;

Assign to Map whose key is numeric type

Property file

properties


hoge.fuga.101 = 123456789
hoge.fuga.201 = 456789012

yml


hoge:
  fuga:
    101: 123456789
    201: 456789012

code

@Value("${hoge.fuga}")
private Map<Integer, Long> fuga;

Date format value to LocalDateTime type

When assigning to LocalDate / LocalDateTime type, implement Formatter as below in the setting class and register it in ConversionService.

@Bean
public ConversionService conversionService() {
  Set<FormatterRegistrar> registrars = new HashSet<>();
  registrars.add(dateTimeFormatterRegistrar());

  FormattingConversionServiceFactoryBean factory = new FormattingConversionServiceFactoryBean();
  factory.setFormatterRegistrars(registrars);
  factory.afterPropertiesSet();
  return factory.getObject();
}

private FormatterRegistrar dateTimeFormatterRegistrar() {
  DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
  registrar.setDateTimeFormatter(dateTimeFormatterFactory());
  registrar.setUseIsoFormat(true);
  return registrar;
}

//Formatter implementation
private DateTimeFormatter dateTimeFormatterFactory() {
  DateTimeFormatterFactoryBean factory = new DateTimeFormatterFactoryBean();
  factory.setPattern("yyyy-MM-dd HH:mm:ss");
  factory.setTimeZone(TimeZone.getDefault());
  factory.afterPropertiesSet();
  return factory.getObject();
}

Assign to LocalDateTime type

Property file

properites


hoge.fuga = 2017-08-01 23:59:59

yml


hoge:
  fuga: 2017-08-01 23:59:59

code

@Value("${hoge.fuga}")
private LocalDateTime fuga;

Assign to LocalDate type

Property file

properites


hoge.fuga = 2017-08-01

yml


hoge:
  fuga: 2017-08-01

code

@Value("${hoge.fuga}")
private LocalDate fuga;

File path format value to Path type

No need to implement a converter or the like. Absolute paths and relative paths are given as samples, but there is no difference in their handling.

Substitute the value of the relative path

Property file

For property files, you will get an error if you do not escape the path delimiter. (In the case of windows environment, Unix / Linux environment is unconfirmed)

properites


hoge.fuga = dir1\\fuga.txt

For yml, you don't need to escape the path delimiter.

yml


hoge:
  fuga: dir1\fuga.txt

code

@Value("${hoge.fuga}")
private Path fuga;

Substitute the absolute path value

Property file

properites


hoge.fuga = D:\\dir1\\dir2\\fuga.txt

yml


hoge:
  fuga: D:\dir1\dir2\fuga.txt

code

@Value("${hoge.fuga}")
private Path path;

String value to enum type

This is a sample to assign the property value to the enum type.

Substitute the resolved enum from the string

Resolve and substitute the corresponding enum from the character string described in the property file. No need to implement a converter or the like.

Property file

properites


hoge.fuga = Gold

yml


hoge:
  fuga: Gold

** enum definition **

enum


public enum Material {
    Bronze,
    Sliver,
    Gold
    ;
}

code

Value("${hoge.fuga}")
private Material fuga;

Substitute the resolved enum from the enumeration field value

Resolve and substitute the corresponding enum from the field value of the enumerator described in the property file (field called label in this example). In this case, implement the following Converter in the setting class and register it in ConversionService.

@Bean
public ConversionService conversionService() {
  Set<Converter<?, ?>> converters = new HashSet<>();
  converters.add(new StringToMaterialConverter());

  FormattingConversionServiceFactoryBean factory = new FormattingConversionServiceFactoryBean();
  factory.setConverters(converters);

  factory.afterPropertiesSet();
  return factory.getObject();
}
import com.example.lib.constants.Material;
import org.springframework.core.convert.converter.Converter;

public class StringToMaterialConverter implements Converter<String, Material> {

  @Override
  public Material convert(String value) {
    return Material.lookup(value);
  }

}

Property file

properites


hoge.fuga =Money

yml


hoge:
  fuga:Money

** enum definition **

enum


public enum Material {
    Bronze("copper"),
    Sliver("Silver"),
    Gold("Money")
    ;

    Material(String label) {
        this.label = label;
    }

    private String label;

    public String getLabel() {
        return this.label;
    }

    public static Material lookup(String label) {
        return Arrays.stream(Material.values())
                .filter(material -> material.getLabel().equals(label))
                .findFirst().orElseThrow(() -> new RuntimeException("unknown label : " + label));
    }

}

code

Value("${hoge.fuga}")
private Material fuga;

Recommended Posts

Sample code to assign a value in a property file to a field of the expected type
Convert Map <K, V1> to Map <K, V2> (Convert Map Value)
Convert an array of strings to numbers
How to convert a value of a different type and assign it to another variable
Sample code to assign a value in a property file to a field of the expected type
Procedure to make the value of the property file visible in Spring Boot
Sample program that returns the hash value of a file in Java
The story of forgetting to close a file in Java and failing
How to change the value of a variable at a breakpoint in intelliJ
How to convert a value of a different type and assign it to another variable
Sample code to get the values of major SQL types in Java + MySQL 8.0
I hate this kind of code! A collection of anti-patterns actually seen in the field
[ruby] How to assign a value to a hash by referring to the value and key of another hash
Determine that the value is a multiple of 〇 in Ruby
When I switched to IntelliJ, I got a lot of differences in the encoding of the properties file.
How to specify an array in the return value / argument of the method in the CORBA IDL file
Sample code to get the values of major SQL types in Java + Oracle Database 12c
It doesn't respond to the description in .js of the packs file
I tried to write code like a type declaration in Ruby
I tried to make the "Select File" button of the sample application created in the Rails tutorial cool
Fix the file name of war to the one set in Maven
Add a time stamp to the JAR file name in Gradle
Sample code to call the Yahoo! Local Search API in Java
[chown] How to change the owner of a file or directory
I made a tool to output the difference of CSV file
I want to change the value of Attribute in Selenium of Ruby
How to get the length of an audio file in java
How to increment the value of Map in one line in Java
A fix to prevent the increase in the number of DB connections in the custom authentication provider of the Cognos SDK sample
I tried to make a sample program using the problem of database specialist in Domain Driven Design
I tried to make a parent class of a value object in Ruby
Sample code to get key JDBC type values in Java + H2 Database
How to find out the Java version of a compiled class file
How to get the setting value (property value) from the database in Spring Framework
How to get the absolute path of a directory running in Java
Android development, how to check null in the value of JSON object
Samshin on the value of the hidden field
Sample to unzip gz file in Java
[Note] [Beginner] How to write when changing the value of an array element in a Ruby iterative statement
Creating a sample program using the problem of a database specialist in DDD Improvement 2
How to get the ID of a user authenticated with Firebase in Swift
Sample source code for finding the least common multiple of multiple values in Java
Creating a sample program using the problem of a database specialist in DDD Improvement 1
Pay attention to the boundary check of the input value when using the float type
How to make a unique combination of data in the rails intermediate table
How to set environment variables in the properties file of Spring boot application
I made a sample of how to write delegate in SwiftUI 2.0 using MapKit
A memorandum to clean up the code Ruby
Make a margin to the left of the TextField
Measure the size of a folder in Java
Set the time of LocalDateTime to a specific time
About the solution of the error that occurred when trying to create a Japanese file of devise in the Docker development environment
[Ruby] Code to display the day of the week
How to bind to property file in Spring Boot
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
[Spring Boot] How to refer to the property file
I want to get the value in Ruby
[Jackson] A story about converting the return value of BigDecimal type with a custom serializer.
[Java] Integer information of characters in a text file acquired by the read () method
Note (sample code) that added a plant block like Sweet berry of 1.14 in Minecraft 1.12.2
Install multiple submit buttons in Rails View to get the value of the pressed button
How to save a file with the specified extension under the directory specified in Java to the list
Pass arguments to the method and receive the result of the operation as a return value
Input restriction function sample source code of JTextField (Example Validation: numerical value from 1 to 30)