Spring-boot参数化

时间:2018-03-27 05:44:09

标签: java spring spring-boot

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

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

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

PS:我给出的配置是项目特定的,并使用它们来避免代码中的硬编码。

4 个答案:

答案 0 :(得分:0)

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

前:

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

答案 1 :(得分:0)

在资源文件夹中创建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.properties文件中指定的值,其名称为'prefix'。'变量的名称'。

或者您可以使用

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

起初更容易,但对于更多数量的属性而言不是很容易维护。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

如果要将其他文件指定为属性,请执行下面提到的更改。

摘录:

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