1.spring-boot框架初始
spring-boot是
spring
系列下的致力于帮助开发者快速方便搭建项目的工具,并且便于运行部署,特别适用于微服务架构搭建。
本来想从零开始,但是发现简书已有很多文章,在这里就不赘述了,查看spring-boot专题了解更多内容。
首先说一下使用spring-boot
开始项目的一些注意事项(针对新手):
XML
,真的很冗杂annotation
注解和java config
spring-boot
提供的一系列starter
开始你的项目spring-boot
只是帮你更好的开始一个项目,而不是一个应用框架IDEA
开发为了不与其他文章过于相似,此系列文章一律采用gradle
作为构建工具,gradle参考官网介绍,对于maven
项目,gradle init
可以一键转化为gradle项目(肯定需要修改)。
新建文件夹bootmkdir boot
,在boot根目录执行gradle init --type java-library
,修改build.gradle
添加依赖compile 'org.springframework.boot:spring-boot-starter-web'
,新建Application.java
:
@SpringBootApplication public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
写一个简单的controller
@Controller public class PublicController { @RequestMapping("/") @ResponseBody String home() { return "Hello World!"; } }
boot
几乎所有配置都在application.properties
里,新建src/main/resources/application.properties,修改端口号server.port=8090
,命令行启动gradle bootRun
查看http://localhost:8090,Hello World!
。
添加其他功能只需要添加对应的starter
然后配置即可,比如通常会用到的一些starter
:
'org.springframework.boot:spring-boot-starter-web' // web项目 'org.springframework.boot:spring-boot-starter-data-jpa' // JPA对应DAO 'org.springframework.boot:spring-boot-starter-security' // 权限管理 'org.springframework.boot:spring-boot-starter-thymeleaf' // view层,替代JSP 'org.springframework.boot:spring-boot-devtools' // 开发工具,热加载
最后说一下目录结构,一般而言是这样:
|-- build.gradle |-- src |----|-- main |---------|-- java |--------------|-- com.project |---------------------|-- controller |---------------------|-- service |---------------------|-- repository |---------------------|-- entity |---------|-- resources |--------------|-- application.properties |--------------|-- application-dev.properties |--------------|-- application-pro.properties
我推荐这样:
|-- build.gradle |-- src |----|-- main |---------|-- java |--------------|-- com.project |---------------------|-- user |--------------------------|-- controller |--------------------------|-- service |--------------------------|-- repository |--------------------------|-- entity |---------|-- resources |--------------|-- application.properties |--------------|-- application-dev.properties |--------------|-- application-pro.properties
按组件区分,易查看代码,当项目成长到一定程度更加容易拆分。
优质内容筛选与推荐>>