简体   繁体   中英

How to inject value from property file into field?

I have some class:

public class MyResources {

    @Value("${my.value}") // value always is null!!!
    private String PATH_TO_FONTS_FOLDER;
}

and I have a property file:

my.value=/tmp/path

and my config class:

@Configuration
public class MyBeanConfig {
    @Bean
    public MyResources myResources() throws Exception 
    {
        return new MyResources();
    }
}

How can I inject property from my property file into this class field?

You have to mark MyResources with the @Component annotation, for Spring to be able to manage that bean.

This will do the job:

@Component
public class MyResources {

    @Value("${my.value}") // value always is null!!!
    private String PATH_TO_FONTS_FOLDER;
}

One approach would be to move @Value("${my.value}") to MyBeanConfig , and add a constructor to MyResources which accepts the value. For example:

@Configuration
public class MyBeanConfig {
    @Value("${my.value}")
    private String PATH_TO_FONTS_FOLDER;

    @Bean
        public MyResources myResources() throws Exception {
        return new MyResources(PATH_TO_FONTS_FOLDER);
    }
}

But based on the example, there's no need for MyBeanConfig . Simply mark MyResources as @Component (or other as appropriate) to allow Spring to manage the creation of the instance. If Spring creates the instance (instead of using new from the example), then the @Value will be injected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM