第一種方式獲取:
1.application.properties文件
server.port=8088 server.servlet.context-path=/springboot-ActiveMQ/ spring.activemq.broker-url=tcp://localhost:61616 #自定義屬性 url=http://127.0.0.0:8899
2.一個GetPropertiesController測試類
package com.qingfeng.test;
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-ActiveMQ/getProperties
@GetMapping("/getProperties")
public void getProperties() {
//獲取項目端口號server.port=8088
System.out.println("項目端口號為:"+environment.getProperty("server.port"));
//獲取activemq路徑spring.activemq.broker-url=tcp://localhost:61616
System.out.println("獲取activemq路徑為:"+environment.getProperty("spring.activemq.broker-url"));
//獲取自定義屬性url=http://127.0.0.0:8899
System.out.println("獲取自定義屬性路徑為:"+environment.getProperty("url"));
}
}
3.啟動項目訪問http://localhost:8088/springboot-ActiveMQ/getProperties可以看到控制台輸出
項目端口號為:8088 獲取activemq路徑為:tcp://localhost:61616
第二種方式獲取
1.application.properties文件
server.port=8088 server.servlet.context-path=/springboot-ActiveMQ/ spring.activemq.broker-url=tcp://localhost:61616 #自定義屬性 url=http://127.0.0.0:8899
2.Test測試類
package com.qingfeng.test;
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.properties")//讀取application.properties文件
public class Test {
//獲取項目端口號server.port=8088
@Value("${server.port}")
private String servePrort;
//獲取activemq路徑spring.activemq.broker-url=tcp://localhost:61616
@Value("${spring.activemq.broker-url}")
private String activemqUrl;
//獲取自定義屬性
@Value("${url}")
private String url;
@GetMapping("/get")
public void get() {
//獲取項目端口號server.port=8088
System.out.println("項目端口號為:"+servePrort);
//獲取activemq路徑spring.activemq.broker-url=tcp://localhost:61616
System.out.println("獲取activemq路徑為:"+activemqUrl);
//獲取自定義屬性url=http://127.0.0.0:8899
System.out.println("獲取自定義屬性路徑為:"+url);
}
}
3.啟動項目訪問http://localhost:8088/springboot-ActiveMQ/getProperties可以看到控制台輸出
項目端口號為:8088 獲取activemq路徑為:tcp://localhost:61616 獲取自定義屬性路徑為:http://127.0.0.0:8899
