【问题标题】:Spring-boot parameterizingSpring-boot参数化
【发布时间】:2018-03-27 05:44:08
【问题描述】:

我是 Spring-bot 的新手,我需要在资源文件夹中添加一个配置文件并从中读取值。 现在我所做的是我在类路径文件夹中创建了一个“Configuration.properties”文件并调用了程序中的属性

FileReader reader=new FileReader("Configuration.properties");
Properties p=new Properties(); 
p.load(reader);
return p;

有人可以帮助我如何让它从 spring-boot(或类似文件)的 application.properties 文件中调用,从而使我的配置在我创建的 jar 中可用。

PS:我给出的配置是特定于项目的,并且正在使用它们来避免代码内部的硬编码。

【问题讨论】:

标签: java spring spring-boot


【解决方案1】:

在资源文件夹中创建application.properties文件,spring boot会自动找到。

假设你使用这些属性

test.stringProperty=will_be_used
test.integerProperty=42
stringProperty=not_used

然后你可以像这样创建一个配置属性类

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "test")
public static class TestProperties {

    private String stringProperty;
    private Integer integerProperty;

    // getters and setters

}

并使用它

import org.springframework.context.annotation.Configuration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@Configuration
@EnableConfigurationProperties(TestProperties.class)
public class TestConfiguration {

    @Autowired
    private TestProperties config;

    // do whatever with properties

}

然后,自动装配的对象将具有您在 application.propertiesfile 中指定的值,名称为 'prefix'.'name of the variable'。

或者你可以使用

@Value("${stringProperty}")
private String value;

一开始这更容易,但对于更多的属性来说不是很容易维护。

【讨论】:

  • 谢谢@finrod,但是一旦我运行代码,我就会得到空异常。可能是因为我正在编写一个rest api并且属性调用发生在实现类中。请你建议我们如何扩展它要在 Spring-Boot 应用程序中实现的方法,该应用程序创建一个休息 API。
  • 如果我理解正确的话,你想在一个 rest 接口的实现中使用属性值。如果是这种情况,您可以在TestConfiguration 类中创建它,而不是使用@Component(或您用来创建bean 的任何方式)来注释实现。只需在配置类中使用@Bean 注释的方法返回实现的新实例并将属性传递给它的构造函数。
【解决方案2】:

您可以使用@Value 注解来获取属性文件的值。

例如:

@Value("${rest_api_url}")
private String restApiUrl;

【讨论】:

    【解决方案3】:

    需要根据您的应用程序的要求定义属性文件。 你可以在bean中使用@Value注解。
    参考:Externalized ConfigurationProperties and Configuration

    【讨论】:

      【解决方案4】:

      在资源文件夹中创建一个名为application.properties的文件,该文件将自动作为默认属性文件。

      如果您想将其他文件指定为属性,请执行以下更改。

      片段:

      @SpringBootApplication
      @ImportResource("classpath:filename.properties")
      public class Example{
          public static void main(String[] args) {
          SpringApplication.run(Example.class, args);
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-15
        • 2019-03-07
        • 2017-09-11
        • 1970-01-01
        • 2018-02-14
        • 2019-04-19
        • 2018-07-11
        相关资源
        最近更新 更多