Spring Boot的目的是為了簡(jiǎn)化開(kāi)發(fā)基于Spring框架的單體生產(chǎn)級(jí)系統(tǒng)赦肃,開(kāi)發(fā)直接運(yùn)行的Spring程序的框架溅蛉;也可以理解為是一種簡(jiǎn)單的微服務(wù)框架∷穑可以快速的開(kāi)發(fā)基于Spring的Web應(yīng)用船侧,而且避免了復(fù)雜繁瑣的XML配置。
文章中的例子厅各,使用IDEA進(jìn)行開(kāi)發(fā)镜撩,Gradle作為包管理和自動(dòng)化構(gòu)建工具。
注意:執(zhí)行過(guò)程中队塘,如果有依賴包無(wú)法加載的問(wèn)題袁梗,或者其他問(wèn)題,多執(zhí)行幾次
gradle build
確保build可以正確通過(guò)憔古。
第一步遮怜,在IDEA中創(chuàng)建一個(gè)Gradle項(xiàng)目
創(chuàng)建過(guò)程中,選擇User auto-import
其他的默認(rèn)填寫(xiě)就可以鸿市,創(chuàng)建后以后默認(rèn)就有一些文件和目錄锯梁,以下是需要用到的。
- build.gradle??gradle構(gòu)建的腳本焰情,包管理和稍后的構(gòu)建陌凳,都是在腳本中配置的。
- src/main??程序的主程序和配置文件内舟。
- src/main/java 主程序
- src/main/resources 配置文件
- src/test??測(cè)試的主程序代碼和配置文件合敦,結(jié)構(gòu)和主程序相通。
第二部谒获,配置Gradle腳本
內(nèi)容如下:
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
}
}
修改完之后點(diǎn)擊Gradle Tool Window中的刷新按鈕蛤肌,會(huì)自動(dòng)下載對(duì)應(yīng)的依賴包壁却。
第三步 創(chuàng)建Spring Boot的資源配置文件
在src/resources/config
目錄下創(chuàng)建文件application.properties
,指定運(yùn)行web服務(wù)的端口裸准,還有一些之前放在xml中的配置項(xiàng)展东。
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函數(shù),是程序的掛載點(diǎn)炒俱,可以通過(guò)Java執(zhí)行的方式盐肃,直接運(yùn)行該類,就可以通過(guò)SpringBoot來(lái)編寫(xiě)Spring框架的應(yīng)用权悟。
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("通過(guò)SpringBoot來(lái)注入依賴:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}
第五步 通過(guò)注解和類的方式來(lái)進(jìn)行SpringMVC配置
SpringBoot通過(guò)注解的方式來(lái)實(shí)現(xiàn)SpringMVC配置砸王,代替復(fù)雜的XML文件,可以通過(guò)創(chuàng)建一系列不同的類峦阁,進(jìn)行各種相應(yīng)的配置谦铃,首先通過(guò)一個(gè)繼承WebMvcConfigurerAdapter
進(jìn)行基礎(chǔ)的配置,這里使用freemarker作為模版引擎榔昔。通過(guò)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;
}
}
第六步 編寫(xiě)一個(gè)簡(jiǎn)單的控制器
到這里基本的Spring Boot代碼已經(jīng)編寫(xiě)好撒会,通過(guò)@RestController
注解實(shí)現(xiàn)一個(gè)控制器類就可以看到運(yùn)行的效果嘹朗,代碼如下
@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;
}
}
接下來(lái)運(yùn)行Gradle命令,gradle bootRun
或者gradle run
诵肛,就可以運(yùn)行SpringBoot屹培,并且加載Spring MVC框架了。直接執(zhí)行curl http://localhost:8080/demo
或者在瀏覽器中打開(kāi)對(duì)應(yīng)鏈接怔檩,就可以看到效果褪秀。
此外,idea默認(rèn)會(huì)使用windows自帶的gbk編碼珠洗,會(huì)出現(xiàn)中文亂碼問(wèn)題溜歪,要在file encoding
中設(shè)置所有的編碼都是utf8。