Spring Boot 入门

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

Spring Boot建议使用Maven或Gradle,本文以Maven为例。

首先创建一个一般的Maven项目,有一个pom.xml和基本的src/main/java结构。

本文使用eclipse-mars 以及jdk1.7作为测试

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>com.wt.springboot</groupId>
  <artifactId>firstSpringBoot</artifactId>
  <version>1.0.0-SNAPSHOT</version>

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

    <dependencies>
        <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>
                <dependencies>
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                        <version>1.2.5.RELEASE</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>
增加了parent父工程
导入pom文件的时候发现有parent付工程,但是本文并没有简历付工程,编译也没报错,点进去发现是springboot自带的工程 spring-boot-starter-parent包含了大量配置好的依赖管理,在自己项目添加这些依赖的时候不需要写 <version>版本号。
使用父pom虽然简单,但是有些情况我们已经有父pom,不能直接增加<parent>时,可以通过如下方式:
<dependencyManagement>
     <dependencies>
        <dependency>
            <!-- Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.2.3.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
java.version属性

上面pom.xml虽然没有出现这个属性,这里要特别提醒。

Spring默认使用jdk1.6,如果你想使用jdk1.8,你需要在pom.xml的属性里面添加java.version,如下:

<properties> 
    <java.version>1.8</java.version>
</properties>

添加spring-boot-starter-web依赖

Spring通过添加spring-boot-starter-*这样的依赖就能支持具体的某个功能。

我们这个示例最终是要实现web功能,所以添加的是这个依赖。

更完整的功能列表可以查看:using-boot-starter-poms

添加spring-boot-maven-plugin插件

该插件支持多种功能,常用的有两种,第一种是打包项目为可执行的jar包。

在项目根目录下执行mvn package将会生成一个可执行的jar包,jar包中包含了所有依赖的jar包,只需要这一个jar包就可以运行程序,使用起来很方便。该命令执行后还会保留一个XXX.jar.original的jar包,包含了项目中单独的部分。

生成这个可执行的jar包后,在命令行执行java -jar xxxx.jar即可启动项目。

另外一个命令就是mvn spring-boot:run,可以直接使用tomcat(默认)启动项目。

在我们开发过程中,我们需要经常修改,为了避免重复启动项目,我们可以启用热部署。

Spring-Loaded项目提供了强大的热部署功能,添加/删除/修改 方法/字段/接口/枚举 等代码的时候都可以热部署,速度很快,很方便。

想在Spring Boot中使用该功能非常简单,就是在spring-boot-maven-plugin插件下面添加依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>springloaded</artifactId>
        <version>1.2.5.RELEASE</version>
    </dependency>
</dependencies>

添加以后,通过mvn spring-boot:run启动就支持热部署了。

注意:使用热部署的时候,需要IDE编译类后才能生效,你可以打开自动编译功能,这样在你保存修改的时候,类就自动重新加载了。

创建一个应用类

我们创建一个Application类:

@RestController
@EnableAutoConfiguration
public class Application {

    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    @RequestMapping("/now")
    String hehe() {
        return "现在时间:" + (new Date()).toLocaleString();
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
注意

Spring Boot建议将我们main方法所在的这个主要的配置类配置在根包名下。

类似如下结构:

com
 +- example
     +- myproject
         +- Application.java
         |
         +- domain
         |   +- Customer.java
         |   +- CustomerRepository.java
         |
         +- service
         |   +- CustomerService.java
         |
         +- web
             +- CustomerController.java

Application.java中有main方法。

因为默认和包有关的注解,默认包名都是当前类所在的包,例如@ComponentScan, @EntityScan, @SpringBootApplication注解。

@RestController

因为我们例子是写一个web应用,因此写的这个注解,这个注解相当于同时添加@Controller@ResponseBody注解。

@EnableAutoConfiguration

Spring Boot建议只有一个带有该注解的类。

@EnableAutoConfiguration作用:Spring Boot会自动根据你jar包的依赖来自动配置项目。例如当你项目下面有HSQLDB的依赖时,Spring Boot会创建默认的内存数据库的数据源DataSource,如果你自己创建了DataSource,Spring Boot就不会创建默认的DataSource

如果你不想让Spring Boot自动创建,你可以配置注解的exclude属性,例如:

@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}
@SpringBootApplication

由于大量项目都会在主要的配置类上添加@Configuration,@EnableAutoConfiguration,@ComponentScan三个注解。

因此Spring Boot提供了@SpringBootApplication注解,该注解可以替代上面三个注解(使用Spring注解继承实现)。

启动项目SpringApplication.run

启动Spring Boot项目最简单的方法就是执行下面的方法:

SpringApplication.run(Application.class, args);

该方法返回一个ApplicationContext对象,使用注解的时候返回的具体类型是AnnotationConfigApplicationContextAnnotationConfigEmbeddedWebApplicationContext,当支持web的时候是第二个。

除了上面这种方法外,还可以用下面的方法:

SpringApplication application = new SpringApplication(Application.class);
application.run(args);

SpringApplication包含了一些其他可以配置的方法,如果你想做一些配置,可以用这种方式。

除了上面这种直接的方法外,还可以使用SpringApplicationBuilder

new SpringApplicationBuilder()
        .showBanner(false)
        .sources(Application.class)
        .run(args);

当使用SpringMVC的时候由于需要使用子容器,就需要用到SpringApplicationBuilder,该类有一个child(xxx...)方法可以添加子容器。

运行

在IDE中直接直接执行main方法,然后访问http://localhost:8080即可。

另外还可以用上面提到的mvn,可以打包为可执行jar包,然后执行java -jar xxx.jar

或者执行mvn spring-boot:run运行项目。

项目启动后输出如下日志:

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

2017-04-22 22:22:47.396  INFO 7812 --- [           main] com.springboot.main.Application          : Starting Application on XV058ELYZ7T2VGC with PID 7812 (C:\licaishi\firstSpringBoot\target\classes started by Administrator in C:\licaishi\firstSpringBoot)
2017-04-22 22:22:47.403  INFO 7812 --- [           main] com.springboot.main.Application          : No profiles are active
2017-04-22 22:22:47.557  INFO 7812 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@46160dbd: startup date [Sat Apr 22 22:22:47 CST 2017]; root of context hierarchy
2017-04-22 22:22:49.089  INFO 7812 --- [           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-04-22 22:22:50.667  INFO 7812 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-04-22 22:22:50.700  INFO 7812 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-04-22 22:22:50.703  INFO 7812 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.28
2017-04-22 22:22:50.899  INFO 7812 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-04-22 22:22:50.899  INFO 7812 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3348 ms
2017-04-22 22:22:51.806  INFO 7812 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2017-04-22 22:22:51.816  INFO 7812 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-04-22 22:22:51.817  INFO 7812 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-04-22 22:22:51.818  INFO 7812 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-04-22 22:22:51.818  INFO 7812 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
2017-04-22 22:22:52.114  INFO 7812 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@46160dbd: startup date [Sat Apr 22 22:22:47 CST 2017]; root of context hierarchy
2017-04-22 22:22:52.301  INFO 7812 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String com.springboot.main.Application.home()
2017-04-22 22:22:52.302  INFO 7812 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/now]}" onto java.lang.String com.springboot.main.Application.hehe()
2017-04-22 22:22:52.311  INFO 7812 --- [           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-04-22 22:22:52.312  INFO 7812 --- [           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)
2017-04-22 22:22:52.381  INFO 7812 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-04-22 22:22:52.382  INFO 7812 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-04-22 22:22:52.478  INFO 7812 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-04-22 22:22:52.764  INFO 7812 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-04-22 22:22:52.879  INFO 7812 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-04-22 22:22:52.885  INFO 7812 --- [           main] com.springboot.main.Application          : Started Application in 6.376 seconds (JVM running for 7.045)
2017-04-22 22:23:44.058  INFO 7812 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-04-22 22:23:44.058  INFO 7812 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2017-04-22 22:23:44.095  INFO 7812 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 36 ms

以上是Spring Boot基础的内容,有些不全面的地方或者读者有更多疑问,可以查看Spring Boot完整文档

关于Spring Boot更多的内容可以继续关注本博客。













  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值