SpringBoot项目(二)创建SpringBoot工程
2.1 Parent工程
2.1.1创建Maven工程
选择Create a simple project
由于是父工程,Packaging选择pom。
让这个父工程继承spring-boot-starter-parent。
spring-boot-starter-parent的基本功能有哪些?
1. 定义了 Java 编译版本为 1.8 。
2. 使用 UTF-8 格式编码。
3. 继承自 spring-boot-dependencies,这个里边定义了依赖的版本,也正是因为继承了这个依赖,所以我们在写依赖时才不需要写版本号。
4. 执行打包操作的配置。
5. 自动化的资源过滤。
6. 自动化的插件配置。
7. 针对 application.properties 和 application.yml 的资源过滤,包括通过 profile 定义的不同环境的配置文件,例如 application-dev.properties 和 application-dev.yml。
2.1.2配置相关插件的版本
有些插件的版本,在spring-boot-starter-parent也没有声明,因此klcms-parent工程中进行统一管理。如下所示:
2.2 Provider工程
创建Maven工程 klcms-provider ,服务提供者。Packaging选择jar。
在klcms-parent项目上右键,New 》Project》Maven》Maven Module
2.3 Web工程
2.3.1 创建Maven工程klcms-web
Packaging选择jar,过程同上。
2.3.2 配置pom.xml
配置依赖项
说明:spring-boot-starter-web依赖项中包含了以下各个模块:
org.springframework.boot.spring-boot-starter
org.springframework.boot.spring-boot-starter-tomcat
org.springframework.spring-web
org.springframework.spring-webmvc
org.hibernate.hibernate-validator
com.fasterxml.jackson.core.jackson-databind
配置静态资源打包
pom文件中添加了“spring-boot-maven-plugin”插件。在添加了该插件之后,当运行“mvn package”进行打包时,会打包成一个可以直接运行的 JAR 文件,使用“java -jar”命令就可以直接运行。
maven-compiler-plugin用来编译Java代码,maven-resources-plugin则用来处理资源文件,拷贝main resources到main output directory,拷贝test resources到test output directory。
2.3.3 WebMainApplication类
在src/main/java目录下创建一个类WebMainApplication,作为主启动类。
添加注解@SpringBootApplication
添加启动代码:SpringApplication.run(WebMainApplication.class, args);
@SpringBootApplication包含了自动配置和组件扫描相关的注解。
2.3.4 启动运行或调试
尝试运行或调试,看是否正常启动。
WebMainApplication上右键》debug as 》Java Application
报错1:
Description:
Cannot determine embedded database driver class for database type NONE
Action:
If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
解决方案:由于没有klcms-provider暂未设置数据库连接属性,先将对klcms-provider的引用注释,klcms-web工程正常后,再进行引用。
报错2:
throw new SilentExitException();
Spring Boot项目使用了spring-boot-devtools工具且在Eclipse中Debug调试会自动跳转到这个方法:
public static void exitCurrentThread() {
throw new SilentExitException();
}
解决方法:
Eclipse->【Preferences】->【Java】->【Debug】:去掉【Suspend execution on uncaught exceptions】前面的勾。
2.3.5 添加控制器测试
@RestController
public class UserController {
@RequestMapping(value = "/user/index", method = RequestMethod.GET)
public String index()
{
return "index";
}
}