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

Ari*_*car 21 java properties spring-boot

我有一个spring启动应用程序,我想从我的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 {
    ...
}
Run Code Online (Sandbox Code Playgroud)

Wil*_*son 32

您可以使用@PropertySource外部化配置到属性文件.有很多方法可以获得属性:

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

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

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

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

    @Autowired
    private Environment env;

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

}
Run Code Online (Sandbox Code Playgroud)

希望这可以提供帮助

  • 为什么foo无效?如何使用该类? (2认同)
  • @gstackoverflow这只是一个例子。您可以随意使用它。 (2认同)

Sam*_*Sam 9

我建议采用以下方式:

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这里您的新属性文件名是"otherprops.properties",属性名称是"myName".这是在spring boot 1.5.8版中访问属性文件的最简单实现.


小智 5

我创建了以下课程

ConfigUtility.java

@Configuration
public class ConfigUtility {

    @Autowired
    private Environment env;

    public String getProperty(String pPropertyKey) {
        return env.getProperty(pPropertyKey);
    }
} 
Run Code Online (Sandbox Code Playgroud)

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

myclass.java

@Autowired
private ConfigUtility configUtil;

public AppResponse getDetails() {

  AppResponse response = new AppResponse();
    String email = configUtil.getProperty("emailid");
    return response;        
}
Run Code Online (Sandbox Code Playgroud)

application.properties

emailid=sunny@domain.com

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