使用Springboot PropertiesFactoryBean

时间:2019-03-15 05:20:04

标签: spring-boot autowired

我是Springboot PropertiesFactoryBean的新手,想从类路径中注入文件,以便可以将其填充到Map中

Eclipse中属性文件的位置:src / main / resources

文件内容:simple_property.properties:

key1=value1
key2=value2
key3=value3

我的ApplicationConfiguration.java如下所示:

import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
public class ApplicationConfiguration {

    @Bean(name = "simpleMapping")
    public static PropertiesFactoryBean artifactMapping() {
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        bean.setLocation(new ClassPathResource("simple_property.properties"));

        return bean;
    }

}

我有一个要运行的bean的ApplicationRunner接口:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class pCli implements ApplicationRunner {

    @Autowired
    private SomeClass someProgram;

    public static void main(String[] args) {
        SpringApplication.run(pCli.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        someProgram.run(args.getOptionValues("param1").get(0));
    }
}

我无法理解并继续进行操作,如何使用bean读取所有属性?示例如何将属性放入Map的变量中并访问它们? (如果@Autowired已经从classpath加载了属性文件,那么我该如何访问它?)

1 个答案:

答案 0 :(得分:0)

假设您将地图保存在属性文件中,

app.number-map={KEY1:1, KEY2:2, KEY3:3}

您可以通过使用@Value注释注入属性来使用此值。以下是将值注入方法的示例。春季表达式#{${app.number-map}}将在属性文件中获取值。

someMethod(@Value("#{${app.number-map}}") 
        Map<String, Integer> numberMap) {
   // ...
}

请使用application.properties,因为您仍在学习中。这会让您的生活变得轻松。另外,保留单独的配置Bean确实可以帮助您轻松管理和访问属性值。

相关问题