SpringBoot總結之屬性配置

1、SpringBoot簡介spring

SpringBoot是spring團隊提供的全新框架,主要目的是拋棄傳統Spring應用繁瑣的配置,該框架使用了特定的方式來進行配置,從而使開發人員再也不須要定義樣板化的配置。從本質上說springboot不是一門新技術,主要是做用就是簡化spring開發。springboot

(在Eclipse裏使用SpringBoot,須要安裝STS插件)app

2、SpringBoot屬性配置框架

SpringBoot項目,可經過application.properties配置文件,來配置項目相關信息。this

application.properties項目配置文件,打開是空白 裏面能夠配置項目,因此配置項目咱們 alt+/ 都能提示出來。也能夠使用yml文件作爲項目配置文件。spa

1)項目內置屬性插件

application.properties:code

server.port=8080 server.servlet.context-path=/springTest

application.yml:server

server: port: 8080 servlet: context-path: /springTest

2)自定義屬性blog

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") @ResponseBody public 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; } }
相關文章
相關標籤/搜索