這篇文章主要介紹怎么使用Spring Boot快速創(chuàng)建一個(gè)web項(xiàng)目。
快速開始
增加maven配置
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
詳情: pom.xml
創(chuàng)建controller
@RestController
public class HelloController {
@RequestMapping
public String hello() {
return "hello,world!";
}
}
創(chuàng)建啟動類
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
詳情: Application.java
運(yùn)行
直接運(yùn)行main方法,在瀏覽器打開http://127.0.0.1:8080/即可看到結(jié)果
思考
1. 開發(fā)一個(gè)web項(xiàng)目真的只需要這么少的依賴嗎入挣?
當(dāng)然不是硝拧。在pom文件上按下ctrl+alt+shift+u(idea項(xiàng)目)你會發(fā)現(xiàn),我們的web項(xiàng)目其實(shí)是Spring Boot幫我們集成了springmvc和tomcat障陶。
2. Application是如何掃描到我的controller的咸这?
打開SpringBootApplication注解的源碼可以看到它上面有個(gè)ComponentScan注解,也就是會掃描Application當(dāng)前包及其子包下的spring組件
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication
這點(diǎn)我們可以通過再寫一個(gè)啟動類Application2.java來驗(yàn)證媳维。
在Application2上不加ComponentScan注解的情況下,運(yùn)行程序?qū)⒓虞d不到任何controller(因?yàn)閍pp包下沒有)指黎,而加上
@ComponentScan("com.niuhp.springcloud.sample.helloworld")
就可以加載到HelloController和HelloZhController
但如果是
@ComponentScan("com.niuhp.springcloud.sample.helloworld.controller")
則只能加載到HelloController了
3. 如何指定端口州丹?
我們只需要在java啟動程序傳入?yún)?shù)或者直接修改main方法參數(shù)就可以了,Spring Boot支持各種自定義參數(shù)吓揪,這里不再重復(fù)所计,以后找機(jī)會詳細(xì)介紹。
--server.port=自定義端口號
本文代碼位置:helloworld