Spring JavaConfig for java.util.Properties field

后端 未结 6 2065
面向向阳花
面向向阳花 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条回答
  •  深忆病人
    2021-02-13 02:36

    The XML base Way:

    in spring config:

    
    

    in your class:

    @Autowired
    @Qualifier("myProperties")
    private Properties myProperties;
    

    JavaConfig Only

    It looks like there is an annotation:

    @PropertySource("classpath:com/foo/my-production.properties")
    

    Annotating a class with this will load the properties from the file in to the Environment. You then have to autowire the Environment into the class to get the properties.

    @Configuration
    @PropertySource("classpath:com/foo/my-production.properties")
    public class AppConfig {
    
    @Autowired
    private Environment env;
    
    public void someMethod() {
        String prop = env.getProperty("my.prop.name");
        ...
    }
    

    I do not see a way to directly inject them into the Java.util.properties. But you could create a class that uses this annotation that acts as a wrapper, and builds the properties that way.

提交回复
热议问题