Spring Boot的目的是為了簡化開發(fā)基于Spring框架的單體生產級系統(tǒng),開發(fā)直接運行的Spring程序的框架;也可以理解為是一種簡單的微服務框架??梢钥焖俚拈_發(fā)基于Spring的Web應用,而且避免了復雜繁瑣的XML配置。
文章中的例子,使用IDEA進行開發(fā),Gradle作為包管理和自動化構建工具。
注意:執(zhí)行過程中,如果有依賴包無法加載的問題,或者其他問題,多執(zhí)行幾次
gradle build確保build可以正確通過。
第一步,在IDEA中創(chuàng)建一個Gradle項目
創(chuàng)建過程中,選擇User auto-import其他的默認填寫就可以,創(chuàng)建后以后默認就有一些文件和目錄,以下是需要用到的。
- build.gradle??gradle構建的腳本,包管理和稍后的構建,都是在腳本中配置的。
- src/main??程序的主程序和配置文件。
- src/main/java 主程序
- src/main/resources 配置文件
- src/test??測試的主程序代碼和配置文件,結構和主程序相通。
第二部,配置Gradle腳本
內容如下:
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.7.RELEASE")
}
}
group 'com.liuwill.demo'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'
sourceCompatibility = 1.8
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
// tag::jetty[]
compile("org.springframework.boot:spring-boot-starter-web") {
exclude module: "spring-boot-starter-tomcat"
}
compile("org.springframework.boot:spring-boot-starter-jetty")
// end::jetty[]
// tag::actuator[]
compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.boot:spring-boot-starter-aop")
compile("org.springframework:spring-context-support")
compile("org.springframework:spring-tx")
compile "org.springframework:spring-jdbc"
// end::actuator[]
compile('org.freemarker:freemarker:2.3.23')
compile 'mysql:mysql-connector-java:5.1.36'
compile 'com.h2database:h2:1.4.189'
compile 'org.apache.commons:commons-dbcp2:2.1'
compile 'com.alibaba:fastjson:1.2.6'
testCompile group: 'org.testng', name: 'testng', version: '6.9.8'
testCompile 'com.jayway.jsonpath:json-path:2.0.0'
testCompile("org.springframework.boot:spring-boot-starter-test")
testCompile "org.springframework:spring-test"
}
test {
useTestNG{
suites 'src/test/resources/testng.xml'
useDefaultListeners = true
}
}
修改完之后點擊Gradle Tool Window中的刷新按鈕,會自動下載對應的依賴包。
第三步 創(chuàng)建Spring Boot的資源配置文件
在src/resources/config目錄下創(chuàng)建文件application.properties,指定運行web服務的端口,還有一些之前放在xml中的配置項。
server.port=8080
local.server.port = 8080
#MySql Config
spring.datasource.url=jdbc:mysql://localhost/demodb
spring.datasource.username=demo
spring.datasource.password=0123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.initialize=false
第四步 創(chuàng)建Spring Boot的主類
主類中包含Main函數,是程序的掛載點,可以通過Java執(zhí)行的方式,直接運行該類,就可以通過SpringBoot來編寫Spring框架的應用。
package com.liuwill.demo.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import java.util.Arrays;
@SpringBootApplication
public class DemoBootApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(DemoBootApplication.class, args);
System.out.println("通過SpringBoot來注入依賴:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}
第五步 通過注解和類的方式來進行SpringMVC配置
SpringBoot通過注解的方式來實現SpringMVC配置,代替復雜的XML文件,可以通過創(chuàng)建一系列不同的類,進行各種相應的配置,首先通過一個繼承WebMvcConfigurerAdapter進行基礎的配置,這里使用freemarker作為模版引擎。通過ComponentScan注解,可以配置要掃描bean的路徑。
@Configuration
@EnableWebMvc
@EnableTransactionManagement
@EnableAutoConfiguration
@ComponentScan(basePackages = {
"com.liuwill.demo.boot.controller","com.liuwill.demo.boot.dao"
})
public class MvcConfigurer extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver viewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setCache(true);
resolver.setPrefix("");
resolver.setSuffix(".ftl");
resolver.setContentType("text/html; charset=UTF-8");
return resolver;
}
@Bean
public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException {
FreeMarkerConfigurationFactory factory = new FreeMarkerConfigurationFactory();
factory.setTemplateLoaderPaths("classpath:templates", "src/main/resource/templates");
factory.setDefaultEncoding("UTF-8");
FreeMarkerConfigurer result = new FreeMarkerConfigurer();
result.setConfiguration(factory.createConfiguration());
return result;
}
}
第六步 編寫一個簡單的控制器
到這里基本的Spring Boot代碼已經編寫好,通過@RestController注解實現一個控制器類就可以看到運行的效果,代碼如下
@RestController
public class DemoController {
@Autowired
private DemoService demoService;
@Autowired
private DemoUserService demoCommonService;
@RequestMapping("/demo")
public Map index() {
Map resultMap = new HashMap();
resultMap.put("status","success");
resultMap.put("content",demoService.getString());
return resultMap;
}
@RequestMapping(value = "/mobile/{mobile:.+}", method = RequestMethod.GET)
public Object getSingleLoanItem(@PathVariable("mobile") String mobile) {
Map resultMap = new HashMap();
resultMap.put("status","success");
resultMap.put("content",demoCommonService.getUserByMobile(mobile));
return resultMap;
}
}
接下來運行Gradle命令,gradle bootRun或者gradle run,就可以運行SpringBoot,并且加載Spring MVC框架了。直接執(zhí)行curl http://localhost:8080/demo或者在瀏覽器中打開對應鏈接,就可以看到效果。
此外,idea默認會使用windows自帶的gbk編碼,會出現中文亂碼問題,要在file encoding中設置所有的編碼都是utf8。