快速搭建springboot项目,被其快速零配置的特点惊呆了

最近因为项目需要接触了springboot,然后被其快速零配置的特点惊呆了。关于springboot相关的介绍我就不赘述了,大家自行百度google。

一、pom配置

首先,建立一个maven项目,修改pom.xml文件,添加parent依赖。

<parent>

<groupid>org.springframework.boot/<groupid>

<artifactid>spring-boot-starter-parent/<artifactid>

<version>1.4.2.RELEASE/<version>

spring-boot-starter-parent会自动为我们引入spring相关的依赖。

再看dependencies节点:

我们需要引入starter-web,这是开发web项目必须的依赖,springboot默认集成了tomcat服务器,在这里排除了tomcat,引入了NIO服务器undertow。springboot默认服务器端口8080,可以自行修改,后面会介绍。 视图引擎选择velocity,引入starter-velocity即可,具体配置后面介绍。 引入maven插件:

<plugin>

<groupid>org.springframework.boot/<groupid>

<artifactid>spring-boot-maven-plugin/<artifactid>

二、程序入口

在一级包路径下,比如com.xxx,新建一个Application.java。

解释一下注解:

@Configuration:指出该类是 Bean 配置的信息源,相当于XML中的<beans>,一般加在主类上。@EnableAutoConfiguration:让 SpringBoot 根据应用所声明的依赖来对 Spring 框架进行自动配置,由于 spring-boot-starter-web 添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置@ ComponentScan:表示将该类自动发现(扫描)并注册为Bean,可以自动收集所有的Spring组件(@Component , @Service , @Repository , @Controller 等),包括@Configuration类。@SpringBootApplication: @EnableAutoConfiguration、@ComponentScan和@Configuration的合集。@ EnableTransactionManagement:启用注解式事务。

三、配置

在项目resources目录下新建application.properties文件,springboot默认会读取该配置文件,当然你也可以创建一个名为application.yml文件。

3.1 服务器

server.port=8081

server.context-path=/test

将服务器端口修改为8081,并制定根为test,其他配置请自行挖掘。

3.2 日志

springboot默认使用logback,当然你可以使用别的日志,如log4j2。

logging.config=classpath:logback.xml

logging.level.org.springframework.web=DEBUG

指定日志配置文件位置和日志级别

3.3 模板引擎

使用yml文件进行配置,我们看到这种缩进式的配置,可以省略很多重复性的语句。

spring:

velocity:

charset: UTF-8

properties:

input:

encoding: UTF-8

output:

encoding: UTF-8

toolbox-config-location:/templates/toolbox.xml

四、页面以及静态资源(默认)

页面:/resources/templates/

静态资源:/resources/static/

五、控制器

控制器依然使用@Controller注解,或者@RestController(返回json,Controller和ResponseBody合体),我们在templates下新建一个index.vm视图文件,输出hello,world!

六、打包,启动

使用mvn clean package将应用打成一个jar包,比如test.jar。

在命令行执行命令:java -jar test.jar(也可以在IDE中直接执行main方法)

恭喜你,成功启动!

在浏览器输入localhost:8081/test/看一下效果:

快来感受springboot带给你的快感吧!