简体   繁体   English

如何将属性文件中的值注入字段?

[英]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. 您必须使用@Component批注标记MyResources ,以使Spring能够管理该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. 一种方法是将@Value("${my.value}")移至MyBeanConfig ,并向MyResources添加一个接受该值的构造函数。 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 . 但是基于该示例,不需要MyBeanConfig Simply mark MyResources as @Component (or other as appropriate) to allow Spring to manage the creation of the instance. 只需将MyResources标记为@Component(或其他适当的标记),即可让Spring管理实例的创建。 If Spring creates the instance (instead of using new from the example), then the @Value will be injected. 如果Spring创建了实例(而不是使用示例中的new ),则将注入@Value。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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