springboot從外部讀取配置文件

springboot從外部讀取配置文件
--讀取配置文件工具類,用於替換屬性文件對應值
public class ReadConfig{
    private static Logger logger = LoggerFactory.getLogger(ReadConfig.class);
    private static final String CONFIG_URL = "/pshdhx/local.xml";// linux中配置文件路徑



    //讀取配置文件,更改數據文件數據
    public void readConfigData(){
        System.out.println("開始進入讀取local.xml配置文件方法");
        logger.info("開始進入讀取local.xml配置文件方法");
        SAXReader reader = new SAXReader();
        try{
            Map<String,String> porpMap = new HashMap<>(); //存放配置我呢間路徑
            File file = new File(CONFIG_URL);
            if(!file.exists()){
                logger.info("local.xml配置文件不存在");
                return;
            }
            Document document = reader.read(file);
            Element root = document.getRootElement();
            Iterator<?> it = root.elementIterator();
            while(it.hasNext()){
                Element propElement = (Element)it.next();
                protMap.put(protElement.element("key").getText(),progElement.element("value").getText());
            }
            for(String key : progMap.keySet()){
                if(StringUtils.isNotBlank(key)){
                    System.setProperty(key,porpMap.get(key));
                }
            }
            logger.info("配置文件讀取完畢");
        }catch(DocumentException e){
            logger.error(e.getMessage());
        }catch(Exception e){
            logger.error(e.getMessage());
        }finally{




























        }
    }
}


//在主啓動類中main方法中引入配置類
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@Import(value={ApplicationConfiuration.class,
AppDispatcherServletConfiguration.class,
DatabaseLiquiAutoConfiguration.class,
SpringUtils.class})
public class Application(){
    public static void main(String args[]){
        new ReadConfig().readConfigData(); //讀取配置文件,更改屬性文件對應值
        SpringApplication.run(Application.class,args);
    }
}












<?xml version="1.0" encoding="UTF-8"?>
<properties>
    <property>
        <key>server.port</key>
        <chn>端口</chn>
        <value>8102</value>
    </property>






    <!-- 數據源配置 start -->
    <property>
        <key>spring.datasource.druid.master.url</key>
        <chn>主數據源URL</chn>
        <value>
            <![CDATA[jdbc:postgresql://xxxxx:5432/xxxx?useUnicode=true&characterEncoding=UTF-8]]>
        </value>
    </property>






    <!-- redis 配置 start -->
    <property>
        <key>shiro.redis.host</key>
        <chn>redis的IP</chn>
        <value>xx.xx.xxx.xx</value>
    </property>
    <property>
        <key>shiro.redis.port</key>
        <chn>redis的端口</chn>
        <value>6379</value>
    </property>
    <property>
        <key>shiro.redis.password</key>
        <chn>reids的密碼</chn>
        <value>xxxxxx</value>
    </property>
</properties>
 
















發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章