您的位置:首页 > 编程语言 > Java开发

spring-boot入门(一)快速搭建一个web应用

2017-12-06 23:52 676 查看

spring-boot入门(一)快速搭建一个web应用

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。简单点讲使用spring boot只需要添加相关依赖包将自动为我们配置一些常规的东西,避免各种xml配置。下面让我们来快速入手搭建一个web应用。

spring-boot入门一快速搭建一个web应用
继承starter parent

引入相关spring-boot-starter依赖

添加一个controller

启动主类

运行SimpleApplicationStarter

使用applicationproperties进行一些自定义配置

1.继承starter parent

在pom文件中加入如下配置:

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent>


我这里使用的是1.4.2.RELEASE版本,spring相关版本是4.3.4.RELEASE。不同公司使用的spring版本不同可能要切换相应的spring boot版本。继承spring-boot-starter-parent后就不用管理其它相关组件的版本号,starter parent已经设置好了,这样野避免了自己定义版本可能会导致依赖冲突或者不一致等问题。

2.引入相关spring-boot-starter依赖

要搭建一个web应用只需要加入spring-boot-starter-web就行了,是不是非常方便。引入spring-boot-starter-web后我们看看它自动帮我们加入了哪些模块。



spring-boot-starter

spring-boot-starter包含了spring boot的核心模块,自动配置、日志、spring-core、snakeyaml。

spring-boot-starter-tomcat

内嵌的tomcat容器

spring-web、spring-webmvc

web相关的依赖

只需要引入spring-boot-starter-web搭建一个web项目需要的依赖基本都被加进来了,完全不需要担心jar包冲突,版本不兼容等问题,更不需要配置web.xml和springmvc的相关配置。接下来就是一个简单的controller和一个应用启动主类。

3.添加一个controller

控制层处理我们的相关请求,下面直接看代码:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @author JasonLin
* @version V1.0
* @date 2017/11/30
*/
@RestController
public class HelloWorldController {

@Value("${message:hello world!}")
private String message;

@RequestMapping("/")
public String helloWorld(){
return message;
}
}


@RestController

@RestController与@Controller不同的地方是,@RestController不会反视图,等同于@ResponseBody + @Controller复合用法。可以简单理解为@RestController返回的是json格式的数据而不是jsp或者html。

@Value(“${message:hello world!}”)

@Value自动注入属性值,该属性name=message,默认值为hello world!

4.启动主类

spring boot使用一个主类来加载整个web工程,需要注意的是该主类必须位于main/java目录下的某一个包中,直接将主类置于默认包会在启动是提示警告:

** WARNING ** : Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.


主类代码如下,@SpringBootApplication 等同于同时标注 @Configuration @EnableAutoConfiguration @ComponentScan用于表示启动类是一个更为便利的注解。

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SimpleApplicationStarter {

private static final Log LOG = LogFactory.getLog(SimpleApplicationStarter.class);

public static void main(String[] args) {
SpringApplication.run(SimpleApplicationStarter.class, args);
LOG.info("spring-boot-practice is started.");
}
}


5.运行SimpleApplicationStarter

运行simpleApplicationStarter,控制台打印如下日志则表示应用启动成功。

.   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
'  |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::        (v1.4.2.RELEASE)

2017-12-06 23:18:47.082  INFO 10856 --- [           main] com.foo.SimpleApplicationStarter         : Starting SimpleApplicationStarter on DESKTOP-QSORQJP with PID 10856 (D:\idea-workspace\github\spring-boot-practice\spring-boot-practice-simple\target\classes started by LinYu in D:\idea-workspace\github\spring-boot-practice)
2017-12-06 23:18:47.084  IN
dbbd
FO 10856 --- [           main] com.foo.SimpleApplicationStarter         : No active profile set, falling back to default profiles: default
2017-12-06 23:18:47.125  INFO 10856 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3c72f59f: startup date [Wed Dec 06 23:18:47 CST 2017]; root of context hierarchy
2017-12-06 23:18:48.129  INFO 10856 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-12-06 23:18:48.136  INFO 10856 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-12-06 23:18:48.138  INFO 10856 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.6
2017-12-06 23:18:48.191  INFO 10856 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-12-06 23:18:48.192  INFO 10856 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1070 ms
2017-12-06 23:18:48.301  INFO 10856 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-12-06 23:18:48.304  INFO 10856 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-12-06 23:18:48.304  INFO 10856 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-12-06 23:18:48.305  INFO 10856 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-12-06 23:18:48.305  INFO 10856 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-12-06 23:18:48.480  INFO 10856 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3c72f59f: startup date [Wed Dec 06 23:18:47 CST 2017]; root of context hierarchy
2017-12-06 23:18:48.511  INFO 10856 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String com.foo.controller.HelloWorldController.helloWorld()
2017-12-06 23:18:48.514  INFO 10856 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-12-06 23:18:48.514  INFO 10856 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-12-06 23:18:48.528  INFO 10856 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-06 23:18:48.528  INFO 10856 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-06 23:18:48.545  INFO 10856 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-06 23:18:48.610  INFO 10856 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-12-06 23:18:48.638  INFO 10856 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-12-06 23:18:48.640  INFO 10856 --- [           main] com.foo.SimpleApplicationStarter         : Started SimpleApplicationStarter in 1.743 seconds (JVM running for 2.177)
2017-12-06 23:18:48.640  INFO 10856 --- [           main] com.foo.SimpleApplicationStarter         : spring-boot-practice is started.


分析日志我们发现
2017-12-06 23:18:48.638  INFO 10856 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
,spring boot使用内嵌容器,并且默认端口为8080。

Mapped "{[/]}" onto public java.lang.String com.foo.controller.HelloWorldController.helloWorld()
helloWorld()方法已经关联到/路径下。

打开浏览器访问http://localhost:8080/




到此,恭喜你已经成功完成一个最基本的spring boot应用。是不是非常的简单。

6.使用application.properties进行一些自定义配置

在工程的resource目录下新建application.properties文件,spring boot 会在启动的时候自动加载该文件的配置。例如我们在工程中加入如下配置:

#variable
message=Hello JasonLin
#port
server.port=8089


将message变量赋值为Hello JasonLin,同时自定义web访问端口为8089。接下来重新启动工程。



可以看到我们最新的配置已经生效,通过application.properties可以自定义大量配置。在接下来的示例中将展示更多spring boot的特性。

本文相关代码可从这里clone https://github.com/Json-Lin/spring-boot-practice/tree/master/spring-boot-practice-simple
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息