第三章 一个Hello world项目
课程目标:
- 编写项目构建新型
- 介绍项目入口
- 编写程序代码
- 编写测试用例
- 配置gradle wrapper
编写项目构建新型
使用上一节课构建的项目。打开build.gradle文件:

这里主要是修改访问的中央仓库。国内访问国外的中央仓库是很慢的,这里使用阿里云的中央仓库,作为演示。
// 使用了 Maven 的中央仓库(你也可以指定其他仓库)
repositories {
//mavenCentral()
maven {
url 'http://maven.aliyun.com/nexus/content/groups/public/'
}
}
介绍项目入口
使用eclipse导入gradle项目。这里你可能需要使用eclipse的gradle插件。可以参考这篇文件去安装:http://blog.csdn.net/wzj0808/article/details/52267852

程序运行的入口:
@SpringBootApplication
public class InitializrStartApplication {
public static void main(String[] args) {
SpringApplication.run(InitializrStartApplication.class, args);
}
}
这里主要的就是@SpringBootApplication注解,它是一个符合注解。里面最重要的三个注解是
@Configuration //说明该类本身就是IoC容器的配置类,基于JavaConfig形式
@EnableAutoConfiguration //通过@Import将所有符合自动配置条件的bean定义加载到IoC容器中
@ComponentScan //自动扫描符合条件的组件或定义到IoC容器
//运行一个spring的应用程序,该应用程序指定InitializrStartApplication.class作为配置类数据源
SpringApplication.run(InitializrStartApplication.class, args);
编写程序代码

编写测试用例
测试用例里面用到了一些静态方法,导入的时候记得加上static关键字。
package com.waylau.spring.boot.blog.initializrstart;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.hamcrest.Matchers.equalTo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTests {
@Autowired
private MockMvc mockMvc;
@Test
public void testHello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello world")));
}
}
运行项目:

运行单元测试:

过程中遇到无法扫描到controller注解的问题:
http://blog.csdn.net/qq_35357656/article/details/75514704
启动类,它必须放在和有注解的类的同一目录或者父目录才能扫描到注解类。
将controller包移动到启动类下面的包中,启动扫描成功,单元测试成功。

配置gradle wrapper
gradle\wrapper\gradle-wrapper.properties
将版本配置成最新版本:gradle-4.4-bin.zip
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip
然后使用控制台,去到项目根目录,运行命令

因为服务器在国外,下载gradle包就会比较慢。
下载gradle完成,构建完成后,可以使用命令去运行项目。

gradle和gradlew的关系,可以看这篇文章。https://www.zybuluo.com/xtccc/note/275168
简单来说,Gradlew是包装器,自动下载包装里定义好的gradle 版本,保证编译环境统一,gradle 是用本地的gradle。