[JAVA] I want to read the property file with a file name other than application.yml or application- [profile name] .yml with Spring Boot.

This is pretty good! I couldn't find the sample, so make a note.

What I wanted to do

--Make SpringBoot read the yaml property file with a filename other than ʻapplication.yml --At that time, load a file with a profile name attached, such as ʻapplication-test.yml. --Map the loaded property to the Configuration class

In a multi-project configuration, I wanted to put a property file on the project side where common parts were collected, but in application.yml, it was necessary to use another name to batting with the property file on the user side.

Realization method

point

--Specify the property file to load using @PropertySource in the Configuration class --@PropertySource does not support reading yaml files, so create a class for reading so that it can be read.

Source code

The complete source code is here [https://github.com/h-okhs/SpringPropertySourceExample)

Configuration class

Specify the class for reading Yaml with factory of @PropertySource.

FooConfig.java


@Configuration
@ConfigurationProperties(prefix = "foo")
@Component
@PropertySource(value = {"classpath:/foo-config.yml",
    "classpath:/foo-config-${spring.profiles.active}.yml"},
    factory = YamlPropertySourceFactory.class)
@Data
public class FooConfig {

    private BarConfig bar;
    private BazConfig baz;

    @Data
    public static class BarConfig {
        private String setting1;
    }

    @Data
    public static class BazConfig {
        private String setting1;
        private String setting2;
    }
}

Factory class

A source borrowed from somewhere. It seems that Yaml loaded using Spring's YamlPropertiesFactoryBean is converted to Properties and returned as PropertySource.

YamlPropertySourceFactory.java


public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource)
        throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private static Properties loadYamlIntoProperties(EncodedResource resource)
        throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException) {
                throw (FileNotFoundException) e.getCause();
            }
            throw e;
        }
    }
}

Operation check

SpringPropertySourceTest.java


@SpringBootTest
@ActiveProfiles("test")
public class SpringPropertySourceTest {

    @Autowired
    FooConfig fooConfig;

    @Test
    public void test() {
        assertThat(fooConfig.getBar().getSetting1()).isEqualTo("barbar1");
        assertThat(fooConfig.getBaz().getSetting2()).isEqualTo("bazbaz2");

    }
}

bonus

In SpringBoot2.3.0 or later, @PropertySource's $ {spring.profiles.active} cannot be resolved and an error occurs. I wrote it in another article. (I ate a lot of time because of this ...)

Failed to resolve placeholder used for value of @PropertySource in SpringBoot 2.3.0 or later

Recommended Posts

I want to read the property file with a file name other than application.yml or application- [profile name] .yml with Spring Boot.
[Spring Boot] I want to add my own property file and get the value with env.getProperty ().
[Spring Boot] How to refer to the property file
I want to be able to read a file using refile with administrate [rails6]
I tried to clone a web application full of bugs with Spring Boot
I want to monitor a specific file with WatchService
What I was addicted to when developing a Spring Boot application with VS Code
Extract SQL to property file with jdbcTemplate of spring boot
I want to use the sanitize method other than View.
I want to give a class name to the select attribute
I want to control the maximum file size in file upload for each URL in Spring Boot
Read the file under the classpath as a character string with spring
I want to control the default error message of Spring Boot
I want to download a file on the Internet using Ruby and save it locally (with caution)
Procedure to make the value of the property file visible in Spring Boot
I used Docker to solidify the template to be developed with spring boot.
I want to develop a web application!
I want to get a list of only unique character strings by excluding fixed character strings from the file name
Let's create a TODO application in Java 2 I want to create a template with Spring Initializr and make a Hello world
03. I sent a request from Spring Boot to the zip code search API
Sign in to a Spring Boot web application on the Microsoft ID platform
How to set environment variables in the properties file of Spring boot application
From creating a Spring Boot project to running an application with VS Code
How to bind to property file in Spring Boot
I wanted to gradle spring boot with multi-project
I want to get the information of the class that inherits the UserDetails class of the user who is logged in with Spring Boot.
A memo that I was addicted to when making batch processing with Spring Boot
Error handling when the maximum file size is exceeded when uploading a file with Spring Boot
A story that stumbled when deploying a web application created with Spring Boot to EC2
I tried to implement file upload with Spring MVC
[Spring] Read a message from a YAML file with MessageSource
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
I want to display the name of the poster of the comment
I want to dark mode with the SWT app
I wrote a test with Spring Boot + JUnit 5 now
I want to add a delete function to the comment function
I want to get a list of the contents of a zip file and its uncompressed size
Implemented a strong API for "I want to display ~~ on the screen" with simple CQRS
I want to return a type different from the input element with Java8 StreamAPI reduce ()
I tried to modernize a Java EE application with OpenShift.
I want to bring Tomcat to the server and start the application
The first WEB application with Spring Boot-Making a Pomodoro timer-
A story packed with the basics of Spring Boot (solved)
I want to make a list with kotlin and java!
[Java] Deploy the Spring Boot application to Azure App Service
I want to call a method and count the number
Deploy the application created by Spring Boot to Heroku (public) ②
I want to make a function with kotlin and java!
I want to create a form to select the [Rails] category
Deploy the application created by Spring Boot to Heroku (public) ①
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I want to create a Parquet file even in Ruby
I want to distinct the duplicated data with has_many through
I tried to get started with Swagger using Spring Boot
I want to pass the startup command to postgres with docker-compose.
How to change the file name with Xcode (Refactor Rename)
What to do about the "cannot be read or is not a valid ZIP file" error
I want to know the Method of the Controller where the Exception was thrown in the ExceptionHandler of Spring Boot