springboot从任意位置读取properties启动

package com.star.research;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.StandardEnvironment;

import java.io.FileInputStream;
import java.util.Properties;

@SpringBootApplication
public class WebApp {

    private final static String DEFAULT_CONFIG_PATH = "C:\\Users\\建江\\Desktop\\application.properties";

    public static void main(String[] args)
    {
         new SpringApplicationBuilder(WebApp.class).environment(getEnvironment(DEFAULT_CONFIG_PATH)).run(args);
    }

    public static StandardEnvironment getEnvironment(String path)
    {
        StandardEnvironment environment = new StandardEnvironment();
        Properties properties = new Properties();
        try (FileInputStream inputStream = new FileInputStream(path))
        {
            properties.load(inputStream);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        environment.getPropertySources().addLast(new PropertiesPropertySource("application.properties",properties));
        return environment;
    }
}

  

posted @ 2022-05-27 21:37  陈建江  阅读(133)  评论(0)    收藏  举报