前言
此文只是記錄自己簡單學習spring boot的筆記。所以,文章很多只是初步理解,可能存在嚴重錯誤。
一、Spring boot的初步理解
1、spring boot的目標 (摘自:spring-boot參考指南 official 中文)
- 為所有的Spring開發提供一個從根本上更快的和廣泛使用的入門經驗。
- 開箱即用,但你可以通過不采用默認設置來擺脫這種方式。
- 提供一系列大型項目常用的非功能性特征(比如,內嵌服務器,安全,指標,健康檢測,外部化配置)。
- 絕對不需要代碼生成及XML配置。
2、spring boot代替了什么,Spring、SpringMVC/Struts2、hibernate/Mybatis?
個人理解:代替了spring。用代替/取代來解釋貌似都不好,更准確的可能是封裝了spring,使搭建SSH/SSM更快捷。
傳統的spring有很多xml配置,例如:dataSource、transactionManager、AOP、bean等等xml的配置。即便用注解,也要在xml中配置component-scan等。
但在spring boot,遵循“約定大於配置”,所以盡可能的避免了xml配置。
3、spring boot避免了哪些xml?
主要是spring的application.xml、context等xml。但例如:mybatis.xml、log4j.xml等還是要的。
4、什么是Starter POMs?
Starter POMs是可以包含到應用中的一個方便的依賴關系描述符集合。你可以獲取所有Spring及相關技術的一站式服務,
而不需要翻閱示例代碼,拷貝粘貼大量的依賴描述符。例如,如果你想使用Spring和JPA進行數據庫訪問,
只需要在你的項目中包含 spring-boot-starter-data-jpa 依賴,然后你就可以開始了。
參考參考指南13.4,pdf頁數56/420。
二、Sping boot的建議
1、推薦使用jdk1.8+。(雖然可以在1.6-1.7中使用)
2、servlet容器。
3、Spring Boot兼容Apache Maven 3.2或更高版本;
Spring Boot兼容Gradle 1.12或更高版本。
4、建議使用thymeleaf、velocity、beetl等模版引擎。而不建議使用jsp(雖然可以配置jsp支持)。
三、demo
1、代碼結構(idea)
2、解釋
application.java:入口
GreetingController.java:controller層代碼。
index.html:默認首頁。localhost:8080訪問的頁面即index.html。
greeting.html:請求頁面。
(1、為什么html是在resources中。2、為什么結構是static、templates。3、如何修改此“約定”,把html放到webapp/WEB-INF下。
這些問題在以后學習,此文不討論。)
3、source code

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>VergiLyn</groupId> <artifactId>Spring boot</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.3.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <!-- 模版框架thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <!-- spring boot 單元測試依賴 BEGIN--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- spring boot 單元測試依賴 END--> <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> </project>
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@Controller //@RestController public class GreetingController { @RequestMapping("/greeting") public String greeting(@RequestParam(value="name", required=false, defaultValue="VergiLyn") String name , Model model) { model.addAttribute("name", name); return "greeting"; } }
index.html
<!DOCTYPE HTML> <html> <head> <title>Getting Started: Serving Web Content</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p>Get your greeting <a href="/greeting">here</a></p> </body> </html>
greeting.xml
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Getting Started: Serving Web Content</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p th:text="'Hello, ' + ${name} + '!'" /> </body> </html>
spring boot的單元測試模版
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class TestOfficialDemo { @LocalServerPort private int port; @Autowired private TestRestTemplate restTemplate; @Test public void testGreetingDefault() throws Exception { assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/greeting",String.class))
.contains("VergiLyn");
}
}
4、測試
運行application.java的main()方法,控制台打印:
請求訪問localhost:8080
點擊超鏈接“here”:可以看到用的是defaultValue。
自定義請求greeting:localhost:8080/greeting?name=VergiLyn淡無欲
四、部分解釋
1、@Controller、@RestController、@RequestMapping、@RequestParam是spring的注解,而非spring boot提供的注解。
2、@Controller與@RestController的區別
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Controller { String value() default ""; }
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Controller @ResponseBody public @interface RestController { String value() default ""; }
通過sourceCode的定義可以看出:@RestController在@Controller的基礎上多了@ResponseBody。簡單理解就是:@RestController不能返回html、jsp。
(Rest即webservice中RESTful的rest,可以理解成@RestController主要用來返回json等數據,而非頁面)
3、@SpringBootApplication
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan( excludeFilters = {@Filter(type = FilterType.CUSTOM,classes = {TypeExcludeFilter.class} )} ) public @interface SpringBootApplication { Class<?>[] exclude() default {}; String[] excludeName() default {}; @AliasFor( annotation = ComponentScan.class, attribute = "basePackages" ) String[] scanBasePackages() default {}; @AliasFor( annotation = ComponentScan.class, attribute = "basePackageClasses" ) Class<?>[] scanBasePackageClasses() default {}; }
摘自:參考指南
很多Spring Boot開發者總是使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 注解他們的main類。由於這些
注解被如此頻繁地一塊使用(特別是你遵循以上最佳實踐時),Spring Boot提供一個方便的 @SpringBootApplication 選擇。
該 @SpringBootApplication 注解等價於以默認屬性使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 。
附錄
Serving Web Content with Spring MVC (官方demo)