Spring JavaConfig for java.util.Properties field

后端 未结 6 2141
面向向阳花
面向向阳花 2021-02-13 02:07


Can you please tell me how to use Spring Javaconfig to directly load/autowire a properties file to a java.util.Properties field?

Thanks!

Later edit - st

6条回答
  •  萌比男神i
    2021-02-13 02:49

    application.yml:

    root-something:
        my-properties:
            key1: val1
            key2: val2
    

    Your type-safe pojo:

    import java.util.Properties;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    
    @ConfigurationProperties(prefix = "root-something")
    public class RootSomethingPojo {
    
        private Properties myProperties;
    

    Your container configuration:

    @Configuration
    @EnableConfigurationProperties({ RootSomethingPojo .class })
    public class MySpringConfiguration {
    

    This will inject the key-value pairs directly into the myProperties field.

提交回复
热议问题