在 Spring Boot 中读取属性文件 [英] Read properties file in Spring Boot

查看:50
本文介绍了在 Spring Boot 中读取属性文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Spring Boot 中从单独的文件中读取属性?

How could I read properties form a separate file in Spring Boot ?

我正在尝试他在这里做的事情.. http://www.mkyong.com/spring/spring-propertysources-example/

I'm trying what he's doing here.. http://www.mkyong.com/spring/spring-propertysources-example/

但它不读取文件?

假设您在资源文件夹中有一个 file.properties.

say you have a file.properties in the resources folder.

你应该把:

  spring.configuration.location: classpath:file.properties

在 application.properties 中指向文件.

in application.properties to point to the file.

然后在你的 MyConfig 类中

Then in your MyConfig class

@Service
public class MyConfig{

    @Value("${prop.one}")
    private String propOne;

这不应该吗?我做错了什么

Shouldn't this work? what am I doing wrong

是否有在某处执行此操作的简单示例?

Is there a simple example of doing this somewhere?

谢谢!

推荐答案

最简单的方法是创建一个 application.properties 将驻留在你的 jar 的根目录

The simplest way to do this is to create an application.properties that will reside at the root of your jar

src
  main
    resources
      application.properties

Spring Boot 会将此文件作为属性文件自动加载.这是 spring boot 的一个特殊功能,可以自动查找 application.properties.对于常规 Spring,您需要指定属性文件的位置.他们正在演示如何使用常规弹簧添加新的属性文件.

Spring boot will autoload this file as a properties file. This is a special feature of spring boot to look for the application.properties automatically. With regular Spring, you need to specify where the properties file is. They are demonstrating how to add a new properties file with regular spring.

对于标准 application.properties 中的单独属性文件,您可以添加 @PropertySource 注释到您的配置类.此注解会将属性加载到 spring 环境中.

For a separate properties file from the standard application.properties, you can add the @PropertySource annotation to your configuration class. This annotation will load the properties into the spring environment.

这篇关于在 Spring Boot 中读取属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆