欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot简单例子

程序员文章站 2022-04-09 09:14:06
...

创建一个maven工程,对应的pom.xml文件:

 <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <!-- Spring Boot 启动父依赖 -->
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.2.4.RELEASE</version></parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties> <dependencies>
  <!-- Spring Boot web依赖 -->
<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>
  • 120
  • 21

SpringBoot应用部署到Tomcat下的配置方法用于tomcat版本问题的朋友

  1. 将打包方式改成war

  2. 配置嵌入Tomcat中的方式 
    这里有两种方式可选择:

    方式一:用spring-boot内置的tomcat库, 并指定你要部署到Tomcat的版本

    <properties>
        <tomcat.version>7.0.69</tomcat.version>
    </properties>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-juli</artifactId>
        <version>${tomcat.version}</version>
    </dependency>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    方式二:不用spring-boot内置的tomcat库(强烈推荐这种方式!!)

    <!-- 打war包时加入此项, 告诉spring-boot tomcat相关jar包用外部的,不要打进去 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
  3. 在项目启动的时候报了一个
    16:48
    www.baidu.com
    的错误,检查之后发现项目启动配置的jdk版本是1.6.0_18,换成1.7.0_72版本之后就没问题了

版本采用1.2.4,非官网最新版,但属于稳定版本


创建一个启动类 Application.java

我们的main方法通过调用run,将业务委托给了spring Boot的SpringApplication类。SpringApplication将引导我们的应用,启动Spring,相应地启动被自动配置的Tomcat web服务器。我们需要将 Example.class 作为参数传递给run方法来告诉SpringApplication谁是主要的Spring组件。为了暴露任何的命令行参数,args数组也会被传递过去。

package com.lkl.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

运行main方法


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

2015-08-25 22:53:35.484  INFO 554 --- [           main] com.lkl.springboot.Application       : Starting Application on mac.local with PID 554 (/Users/liaokailin/code/github/blog-springboot/target/classes started by lkl in /Users/liaokailin/code/github/blog-springboot)
2015-08-25 22:53:35.561  INFO 554 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]328908cd: startup date [Tue Aug 25 22:53:35 CST 2015]; root of context hierarchy
2015-08-25 22:53:36.395  INFO 554 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver': 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]]
2015-08-25 22:53:37.404  INFO 554 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2015-08-25 22:53:37.796  INFO 554 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2015-08-25 22:53:37.798  INFO 554 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.23
2015-08-25 22:53:37.955  INFO 554 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2015-08-25 22:53:37.955  INFO 554 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2397 ms
2015-08-25 22:53:38.813  INFO 554 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2015-08-25 22:53:38.818  INFO 554 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2015-08-25 22:53:38.819  INFO 554 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2015-08-25 22:53:39.075  INFO 554 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]328908cd: startup date [Tue Aug 25 22:53:35 CST 2015]; root of context hierarchy
2015-08-25 22:53:39.151  INFO 554 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" 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)
2015-08-25 22:53:39.151  INFO 554 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],methods=[],params=[],headers=[],consumes=[],produces=[text/html],custom=[]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2015-08-25 22:53:39.180  INFO 554 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-08-25 22:53:39.180  INFO 554 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-08-25 22:53:39.232  INFO 554 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-08-25 22:53:39.326  INFO 554 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2015-08-25 22:53:39.430  INFO 554 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2015-08-25 22:53:39.433  INFO 554 --- [           main] com.lkl.springboot.Application       : Started Application in 4.829 seconds (JVM running for 5.238)

spring boot已经启动,内嵌tomcat容器,监听为8080端口

就是这么简单,一个spring boot 的程序就创建了。

@SpringBootApplication 注解

SpringBootApplication注解源码如下:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {

    /**
     * Exclude specific auto-configuration classes such that they will never be applied.
     * @return the classes to exclude
     */
    Class<?>[] exclude() default {};

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 12
  • 13
  • 14

@Configuration : 表示Application作为sprig配置文件存在
@EnableAutoConfiguration: 启动spring boot内置的自动配置
@ComponentScan : 扫描bean,路径为Application类所在package以及package下的子路径,这里为com.lkl.springboot,在spring boot中bean都放置在该路径已经子路径下。

构建REST工程

创建一个package:com.lkl.springboot.controller 保存controller

构建 HelloWorldController.java

 package com.lkl.springboot.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/springboot")
public class HelloWorldController {

    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public String sayWorld(@PathVariable("name") String name) {
        return "Hello " + name;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

再次执行 Application 然后访问http://localhost:8080/springboot/zhangsan

得到结果:
Hello zhangsan