如何使用 Spring Boot 从 java 属性文件中读取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38281512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:10:47  来源:igfitidea点击:

How to read data from java properties file using Spring Boot

javapropertiesspring-boot

提问by Arif Acar

I have a spring boot application and I want to read some variable from my application.propertiesfile. In fact below codes do that. But I think there is a good method for this alternative.

我有一个 Spring Boot 应用程序,我想从我的application.properties文件中读取一些变量。事实上,下面的代码就是这样做的。但我认为这种替代方法有一个很好的方法。

Properties prop = new Properties();
InputStream input = null;

try {
    input = new FileInputStream("config.properties");
    prop.load(input);
    gMapReportUrl = prop.getProperty("gMapReportUrl");
} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    ...
}

采纳答案by Wilson

You can use @PropertySourceto externalize your configuration to a properties file. There is number of way to do get properties:

您可以使用@PropertySource将您的配置外部化到一个属性文件。有多种方法可以获取属性:

1. Assign the property values to fields by using @Valuewith PropertySourcesPlaceholderConfigurerto resolve ${}in @Value:

1. 使用@ValuewithPropertySourcesPlaceholderConfigurer解析${}in将属性值分配给字段@Value

@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {

    @Value("${gMapReportUrl}")
    private String gMapReportUrl;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

2. Get the property values by using Environment:

2. 使用Environment以下方法获取属性值:

@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {

    @Autowired
    private Environment env;

    public void foo() {
        env.getProperty("gMapReportUrl");
    }

}

Hope this can help

希望这可以帮助

回答by Sam

i would suggest the following way:

我会建议以下方式:

@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
    @Value("${myName}")
    private String name;

    @RequestMapping(value = "/xyz")
    @ResponseBody
    public void getName(){
        System.out.println(name);
    }
}

Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.

这里您的新属性文件名为“otherprops.properties”,属性名为“myName”。这是 Spring Boot 1.5.8 版本中访问属性文件的最简单实现。

回答by Sunny

I have created following class

我创建了以下课程

ConfigUtility.java

配置实用程序

@Configuration
public class ConfigUtility {

    @Autowired
    private Environment env;

    public String getProperty(String pPropertyKey) {
        return env.getProperty(pPropertyKey);
    }
} 

and called as follow to get application.properties value

并按如下方式调用以获取 application.properties 值

myclass.java

我的类

@Autowired
private ConfigUtility configUtil;

public AppResponse getDetails() {

  AppResponse response = new AppResponse();
    String email = configUtil.getProperty("emailid");
    return response;        
}

application.properties

应用程序属性

[email protected]

[email protected]

unit tested, working as expected...

单元测试,按预期工作......

回答by Anuj Dhiman

We can read properties file in spring boot using 3 way

我们可以使用 3 种方式在 Spring Boot 中读取属性文件

1. Read value from application.properties Using @Value

1. 使用@Value 从 application.properties 读取值

map key as

映射键为

public class EmailService {

 @Value("${email.username}")
 private String username;

}

}

2. Read value from application.properties Using @ConfigurationProperties

2. 使用@ConfigurationProperties 从 application.properties 读取值

In this we will map prefix of key using ConfigurationProperties and key name is same as field of class

在这里,我们将使用 ConfigurationProperties 映射键的前缀,键名与类的字段相同

  @Component
   @ConfigurationProperties("email")
    public class EmailConfig {

        private String   username;
    }

3. Read application.properties Using using Environment object

3.使用环境对象读取application.properties

public class EmailController {

公共类电子邮件控制器 {

@Autowired
private Environment env;

@GetMapping("/sendmail")
public void sendMail(){     
    System.out.println("reading value from application properties file  using Environment ");
    System.out.println("username ="+ env.getProperty("email.username"));
    System.out.println("pwd ="+ env.getProperty("email.pwd"));
}

Reference : how to read value from application.properties in spring boot

参考:如何在spring boot中从application.properties中读取值