SpringBoot获得application.properties中数据的值
第一种方式获取:
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