SpringBoot-基于Maven工程使用SpringBoot

Spring Boot

SpringBoot是一个社区反馈推动的项目。SpringBoot可以说是至少五年来Spring乃至整个Java社区最有影响力的项目之一。SpringBoot主要包括以下特性:

  1. 直接嵌入Tomcat,Jetty或者Undertow作为Servlet container。从此之后再也不用将应用程序打包成war然后上传到application server里面了。
  2. 提供了starter POM,能够非常方便的进行包管理,很大程度上减少了jar hell或者dependency hell。
  3. 自动进行Spring框架的配置,节省程序员大量的时间和精力,能够让程序员专注在业务逻辑代码的编写上。
  4. 不需要任何第三方系统,Spring Boot自带了可以用于生产环境的程序状态信息和健康状态。同时可以让应用程序非常方便的读取外部的配置信息。
  5. 完全不需要任何代码的自动生成。更不需要用xml来进行框架配置

基于Maven工程使用SpringBoot

新建Maven工程,编写pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>20171111</groupId>
  <artifactId>springboot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>springboot</name>
  <url>http://maven.apache.org</url>

  <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.3.2.RELEASE</version>
      <relativePath></relativePath>
  </parent>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>
  <build>
      <plugins>
          <plugin>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-maven-plugin</artifactId>
          </plugin>
      </plugins>
  </build>
</project>

编写main函数:

在这里标记HelloworldDemoApplication class为SpringBootApplication,SpringBoot在后台会根据这个标记进行很多自动配置,比如配置MVC,配置包扫描,注入必要的类,注入自动配置的类等等。

这里的main函数是一个java标准的main函数,这个相当于应用程序入口,servlet container会在启动的时候找到这个入口,启动Spring container,完成初始化。

package springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;

@SpringBootApplication
public class HelloworldDemoApplication implements EmbeddedServletContainerCustomizer{
    public static void main(String[] args){
        SpringApplication.run(HelloworldDemoApplication.class, args);
    }

    public void customize(ConfigurableEmbeddedServletContainer container) {
        // TODO 自动生成的方法存根
        container.setPort(8088);
    }
}

编写 HelloworldRestController类

package springboot;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloworldRestController {
    @RequestMapping("/")
    public String helloworld(){
        return "hello world";
    }
}

选择运行方式为:Maven Build ->对应的窗口里面设置Goals:clean package spring-boot:run,顺便为了方便把下面的Skip Tests也勾上,然后run。

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

2017-11-11 23:41:56.105  INFO 8407 --- [           main] springboot.HelloworldDemoApplication     : Starting HelloworldDemoApplication on pdeMacBook-Pro.local with PID 8407 (/Users/pg/Documents/workspace/springboot/target/classes started by pg in /Users/pg/Documents/workspace/springboot)
2017-11-11 23:41:56.107  INFO 8407 --- [           main] springboot.HelloworldDemoApplication     : No active profile set, falling back to default profiles: default
2017-11-11 23:41:56.147  INFO 8407 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]563b3f89: startup date [Sat Nov 11 23:41:56 CST 2017]; root of context hierarchy
2017-11-11 23:41:57.262  INFO 8407 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean ‘beanNameViewResolver‘ with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2017-11-11 23:41:58.061  INFO 8407 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8088 (http)
2017-11-11 23:41:58.091  INFO 8407 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-11-11 23:41:58.093  INFO 8407 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.30
2017-11-11 23:41:58.224  INFO 8407 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-11-11 23:41:58.224  INFO 8407 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2077 ms
2017-11-11 23:41:58.590  INFO 8407 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: ‘dispatcherServlet‘ to [/]
2017-11-11 23:41:58.595  INFO 8407 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: ‘characterEncodingFilter‘ to: [/*]
2017-11-11 23:41:58.596  INFO 8407 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: ‘hiddenHttpMethodFilter‘ to: [/*]
2017-11-11 23:41:58.596  INFO 8407 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: ‘httpPutFormContentFilter‘ to: [/*]
2017-11-11 23:41:58.596  INFO 8407 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: ‘requestContextFilter‘ to: [/*]
2017-11-11 23:41:58.947  INFO 8407 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]563b3f89: startup date [Sat Nov 11 23:41:56 CST 2017]; root of context hierarchy
2017-11-11 23:41:59.028  INFO 8407 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String springboot.HelloworldRestController.helloworld()
2017-11-11 23:41:59.032  INFO 8407 --- [           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-11-11 23:41:59.032  INFO 8407 --- [           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-11-11 23:41:59.056  INFO 8407 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-11 23:41:59.056  INFO 8407 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-11 23:41:59.091  INFO 8407 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-11 23:41:59.207  INFO 8407 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-11-11 23:41:59.291 ERROR 8407 --- [           main] o.a.coyote.http11.Http11NioProtocol      : Failed to start end point associated with ProtocolHandler ["http-nio-8088"]

如果你遇到这种问题:Failed to start end point associated with ProtocolHandler ["http-nio-8088"]

这表明8088端口被占用了,可以通过实现EmbeddedServletContainerCustomizer接口修改SpringBoot内置的tomcat端口来解决端口被占用的问题:

package springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;

@SpringBootApplication
public class HelloworldDemoApplication implements EmbeddedServletContainerCustomizer{
    public static void main(String[] args){
        SpringApplication.run(HelloworldDemoApplication.class, args);
    }

    public void customize(ConfigurableEmbeddedServletContainer container) {
        // TODO 自动生成的方法存根
        container.setPort(8089);
    }
}

修改端口为8089:再次运行:

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

2017-11-11 23:47:48.204  INFO 8449 --- [           main] springboot.HelloworldDemoApplication     : Starting HelloworldDemoApplication on pdeMacBook-Pro.local with PID 8449 (/Users/pg/Documents/workspace/springboot/target/classes started by pg in /Users/pg/Documents/workspace/springboot)
2017-11-11 23:47:48.209  INFO 8449 --- [           main] springboot.HelloworldDemoApplication     : No active profile set, falling back to default profiles: default
2017-11-11 23:47:48.363  INFO 8449 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]48af20f4: startup date [Sat Nov 11 23:47:48 CST 2017]; root of context hierarchy
2017-11-11 23:47:49.230  INFO 8449 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean ‘beanNameViewResolver‘ with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2017-11-11 23:47:50.197  INFO 8449 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8089 (http)
2017-11-11 23:47:50.223  INFO 8449 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-11-11 23:47:50.225  INFO 8449 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.30
2017-11-11 23:47:50.360  INFO 8449 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-11-11 23:47:50.362  INFO 8449 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2001 ms
2017-11-11 23:47:50.761  INFO 8449 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: ‘dispatcherServlet‘ to [/]
2017-11-11 23:47:50.767  INFO 8449 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: ‘characterEncodingFilter‘ to: [/*]
2017-11-11 23:47:50.767  INFO 8449 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: ‘hiddenHttpMethodFilter‘ to: [/*]
2017-11-11 23:47:50.767  INFO 8449 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: ‘httpPutFormContentFilter‘ to: [/*]
2017-11-11 23:47:50.768  INFO 8449 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: ‘requestContextFilter‘ to: [/*]
2017-11-11 23:47:51.092  INFO 8449 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]48af20f4: startup date [Sat Nov 11 23:47:48 CST 2017]; root of context hierarchy
2017-11-11 23:47:51.161  INFO 8449 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String springboot.HelloworldRestController.helloworld()
2017-11-11 23:47:51.164  INFO 8449 --- [           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-11-11 23:47:51.165  INFO 8449 --- [           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-11-11 23:47:51.193  INFO 8449 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-11 23:47:51.194  INFO 8449 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-11 23:47:51.237  INFO 8449 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-11 23:47:51.365  INFO 8449 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-11-11 23:47:51.463  INFO 8449 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8089 (http)
2017-11-11 23:47:51.471  INFO 8449 --- [           main] springboot.HelloworldDemoApplication     : Started HelloworldDemoApplication in 14.261 seconds (JVM running for 19.706)
2017-11-11 23:51:29.888  INFO 8449 --- [nio-8089-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet ‘dispatcherServlet‘
2017-11-11 23:51:29.890  INFO 8449 --- [nio-8089-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet ‘dispatcherServlet‘: initialization started
2017-11-11 23:51:29.920  INFO 8449 --- [nio-8089-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet ‘dispatcherServlet‘: initialization completed in 30 ms

打开浏览器输入:localhost:8089

基于Maven的SpringBoot简单使用就完成了。

时间: 2024-09-29 10:26:24

SpringBoot-基于Maven工程使用SpringBoot的相关文章

使用 lntelliJ IDEA 创建 Maven 工程的springboot项目

IntelliJ IDEA 为后起之秀 得到了越来 广泛 应用.下面的idea软件的界面详情 二.使用 IntelliJ IDEA Maven 工程步骤如下: 2.1 依次选择“file”.“new"."project",创建新项目.出现下面的界面,创建项目时选择 Mave ,但 不必选择项目骨架 直接单击 Next 按钮即可 2.2.输入组织名称.模块名称.项 版本号等信息 2.3.选择项目位置,然后单击 Finish 按钮, 完成项目创建 三 三.springboot项目

springboot基于maven多模块项目搭建(直接启动webApplication)

1. 新建maven项目springboot-module 2.把src删掉,新建module项目 springboot-module-api springboot-module-model springboot-module-service springboot-module-util springboot-module-web 3. 添加模块之间的依赖 3.1   springboot-module.pom 1 <?xml version="1.0" encoding=&qu

记一次springboot下maven工程方式导入pom.xml首行报错

今天maven工程pom.xml报错,错误类型unkown,没有任何提示信息,个人思路先检查一下配置文件的语法格式是否正确,本人因为之前也有类似错误经验,觉得应该是配置问题中的版本问题,最好能找下网上关于该涉及软件之间的版本支持情况,如果找不到可以尝试将版本号调小,还可以参考以前正确配置也是不错呢.我是一开始版本是2.1.5release这个版本改成2.1.4即不再报错了当然里面涉及版本以及只要配置的都可以尝试的调整一下,注意每次都刷新一下,以定位问题所在.<groupId>org.sprin

maven工程仿springboot手写代码区分开发测试生产

读取代码: package com.jz.compute.mc.v2.config; import java.util.Enumeration; import java.util.ResourceBundle; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class PropertiesConfig { public static volatile

java做的一个xml转Excel工具,基于maven工程

说明:适合数据库导出为xml时转成Excel 本工具将上传至GitHub:https://github.com/xiaostudy/xiaostudyAPI3 doc4j的maven依赖 1 <!--xml解析的dom4j--> 2 <!-- https://mvnrepository.com/artifact/dom4j/dom4j --> 3 <dependency> 4 <groupId>dom4j</groupId> 5 <arti

Eclipse中将Maven工程转成SpringBoot工程

一.File ——>New ——>Maven Project 二.新建一个maven的web工程的目录结构如下: 三.会有一个错误:jsp报错. 四.这里我们不用管这个错误,直接将jsp文件删掉,就可以不报错了(因为目前前端我使用的是thymeleaf,使用html页面,所以不用jsp),另,将webapp文件夹下的web.xml文件删除,效果如下: 五.修改pom.xml文件,删掉所有的依赖(dependencies)和build标签. 效果如下: 六.百度搜索springboot,随便找一

基于Maven的SpringBoot项目实现热部署的两种方式

下面我将介绍使用maven构建的SpringBoot项目中实现热部署的两种方式,使得部署变得异常简单,同时两种方式也非常的简单. 热部署 devtools Pom.xml中直接添加依赖即可: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>provided</

SpringBoot 基于web应用开发(请求参数获取,静态资源,webjars)

SpringBoot 基于web应用开发 一.Lombok使用 1.导入依赖库 <dependency>    <groupId>org.projectlombok</groupId>    <artifactId>lombok</artifactId>    <version>1.18.6</version></dependency> 2.安装插件 3.在实体bean使用 @Data    相当于set,ge

我的第一个springboot应用+maven依赖管理

第一步:使用Eclipse创建maven工程SpringBootFirst:工程目录如下 第二步:编写依赖文件pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http: