【问题标题】:Spring Auto Create Properties FileSpring 自动创建属性文件
【发布时间】:2017-10-12 12:06:55
【问题描述】:

我有一个简单的类来使用@PropertySource 来表示属性文件,就像这样

@Component
@PropertySource(value = "file:${user.home}/.cooperp/app-conf.properties")
public class ApplicationProperties {
    @Value("${mysql-location}")
    private String mysqlLocation;

    public String getMysqlLocation() {
        return mysqlLocation;
    }

    public void setMysqlLocation(String mysqlLocation) {
       this.mysqlLocation = mysqlLocation;
    }
}

我知道如果找不到文件,可以添加ignoreResourceNotFound = true,这将使 spring 忽略它的缺失并启动应用程序。

我希望 spring 创建文件它没有找到,而不是忽略或抛出异常。

【问题讨论】:

  • 您需要为此编写代码,这不是@PropertySource 的任务/功能。
  • 在哪里,在 main 方法中?
  • 你为什么要这样做?
  • 我希望文件和属性在需要时使用默认值显示

标签: java spring-boot properties-file


【解决方案1】:

通常我们将属性文件保存在项目目录中。但是如果您的项目需要外部属性,那么您可以检查该文件是否存在于 SpringBootApplication 类中。如果没有,那么您可以在那里创建属性文件。代码示例:

@SpringBootApplication
public class SpringDocBotApplication {

    public static void main(String[] args) {
        File file = new File("EXPECTED PATH"); 

        try{
            if(!file.exists()){
                // create propeties file add properties
            }
        } catch (IOException e) {
         //HANDLE EXCEPTION
        }
        SpringApplication.run(SpringDocBotApplication.class, args);
    }
}

【讨论】:

    猜你喜欢
    • 2018-06-18
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    相关资源
    最近更新 更多