Springboot搭建web项目

最近由于项目须要接触了springboot,而后被其快速零配置的特色惊呆了。关于springboot相关的介绍我就不赘述了,你们自行百度google。java

 

1、pom配置web

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

<parent>json

   <groupId>org.springframework.boot</groupId>浏览器

    <artifactId>spring-boot-starter-parent</artifactId>tomcat

   <version>1.4.2.RELEASE</version>springboot

</parent>服务器

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

 

再看dependencies节点:mybatis


  

  • 咱们须要引入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>

        </plugin>

 

2、程序入口

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

解释一下注解:

  • @Configuration:指出该类是 Bean 配置的信息源,至关于XML中的<beans></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:启用注解式事务。

 

3、配置

    在项目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

 

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

         页面:/resources/templates/

         静态资源:/resources/static/

 

5、控制器

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

 

6、打包,启动

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

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

恭喜你,成功启动!

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


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

 

7、优缺点

  • 优势:简化配置,快速构建应用。我的感受比较适合作微服务。

  • 缺点:坑不少啊,踩过才知道,对spring平台不了解的同窗慎用,仍是老老实实的本身配置吧。

 

下一篇我会来介绍springboot集成mybatis。

 

 

关注老姜谈技术,微信号:helojava,或者扫描下面二维码。

代码改变世界。

相关文章
相关标签/搜索