SpringBoot獲得application.yml中數據的值


第一種方式獲取

1.application.yml文件

server:
  port: 8088  #項目端口號
  servlet:
    context-path: /SpringBoot  #訪問項目名稱
 
zidingyiUrl:
  http://127.0.0.0:8088

  

2.一個TestController測試類

package com.qingfeng.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@PropertySource("classpath:application.yml")//讀取application.yml文件
public class TestController {

	//獲取項目端口號
	@Value("${server.port}")  
	 private String servePrort;  
		
		
	@Value("${server.servlet.context-path}")  
	private String contextPath;  
		
	@Value("${zidingyiUrl}")  
       private String zidingyiUrl; 
	
		//http://localhost:8088/SpringBoot/get
		@GetMapping("/get")
		public void get() {
		//獲取項目端口號server.port=8088
		System.out.println("項目端口號為:"+servePrort);
		//獲取獲取項目名稱
		System.out.println("獲取項目名稱為:"+contextPath);
		//獲取自定義屬性zidingyiUrl
		System.out.println("獲取項目名稱為:"+zidingyiUrl);
		}
}

  

3.啟動項目訪問http://localhost:8088/SpringBoot/get可以看到控制台輸出

項目端口號為:8088
獲取項目名稱為:/SpringBoot

  

第二種方式獲取

1.application.yml文件

server:
  port: 8088  #項目端口號
  servlet:
    context-path: /SpringBoot  #訪問項目名稱
 
zidingyiUrl:
  http://127.0.0.0:8088

  

2.一個GetPropertiesController測試類

package com.qingfeng.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GetPropertiesController {

	@Autowired  
      private Environment environment; 
	
	//http://localhost:8088/SpringBoot/getProperties
	@GetMapping("/getProperties")
	public void getProperties() {
	//獲取項目端口號server.port=8088
	System.out.println("項目端口號為:"+environment.getProperty("server.port"));
	//獲取獲取項目名稱
	System.out.println("獲取項目名稱為:"+environment.getProperty("server.servlet.context-path"));
	//獲取自定義屬性zidingyiUrl
	System.out.println("獲取自定義屬性路徑為:"+environment.getProperty("zidingyiUrl"));
	}
	
}

  

3.啟動項目訪問http://localhost:8088/SpringBoot/ getProperties可以看到控制台輸出

項目端口號為:8088
獲取項目名稱為:/SpringBoot
獲取自定義屬性路徑為:http://127.0.0.0:8088

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM