SpringBoot總結之屬性配置
阿新 • • 發佈:2019-05-08
yml rdb 註入 com gte system app 獲取 body
一、SpringBoot簡介
SpringBoot是spring團隊提供的全新框架,主要目的是拋棄傳統Spring應用繁瑣的配置,該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。從本質上說springboot不是一門新技術,主要是作用就是簡化spring開發。
(在Eclipse裏使用SpringBoot,需要安裝STS插件)
二、SpringBoot屬性配置
SpringBoot項目,可通過application.properties配置文件,來配置項目相關信息。
application.properties項目配置文件,打開是空白 裏面可以配置項目,所以配置項目我們 alt+/ 都能提示出來。也可以使用yml文件做為項目配置文件。
1)項目內置屬性
application.properties:
server.port=8080
server.servlet.context-path=/springTest
application.yml:
server: port: 8080 servlet: context-path: /springTest
2)自定義屬性
application.properties:
server.port=8080 server.servlet.context-path=/springTest hello=hello springboot
application.yml:
server: port: 8080 servlet: context-path: /springTest hello: hello springboot
/** * 獲取自定義屬性只要在字段上加上@Value("${配置文件中的key}"),就可以獲取值 * @author rdb * */ @Controller public class UserController { @Value("${hello}") private String hello; @RequestMapping("/user") @ResponseBodypublic String test() { return hello; } }
3)ConfigurationProperties 配置
配置一個類別下的多個屬性,我們可以@ConfigurationProperties配置到bean裏,使用是直接註入就行了
server: port: 8080 servlet: context-path: /springTest hello: hello springboot test: ip: 192.168.11.11 port: 90
@Component @ConfigurationProperties(prefix="test") public class ConfigBean { private String ip ; private String port; public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } }
@Controller public class UserController { //獲取自定義屬性只要在字段上加上@Value("${配置文件中的key}"),就可以獲取值 @Value("${hello}") private String hello; //@ConfigurationProperties 配置的屬性可以直接註入獲取 @Autowired private ConfigBean configBean; @RequestMapping("/user") @ResponseBody public String test() { System.out.println(configBean.getIp()); System.out.println(configBean.getPort()); return hello; } }
SpringBoot總結之屬性配置