程序小寨

SpringBoot入门

2018-12-18  本文已影响3人  梦中一点心雨

一、Spring Boot简介

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式使得开发人员使用Spring开发极大的简便了配置过程,基本上实现了零配置。
​ <p>Spring Boot有以下几个优点:

​ 1、 没有代码生成,不需要XML配置文件

​ 2、 内嵌Tomcat,Jetty或者Undertow服务器,不需要额外部署web工程到Servlet容器

​ 3、 可以独立运行Spring应用程序

​ 4、 提供了Maven,Gradle两种方法搭建Spring Boot工程

​ 5、 无缝整合其他开源框架(只需要添加开源框架的依赖包,Spring Boot自动完成整合)

​ 6、 提供可以直接在生产环境中使用的功能,如性能指标、应用信息和应用健康检查

二、Spring Boot入门工程搭建:

1、采用Spring官网提供的SPRING INITIALIZR进行搭建。

可以选择Maven Project或者Gradle Project来搭建,然后选择Spring Boot版本,输入Group,Artifact,以及需要的依赖包,然后点击Generate Project,会生成一个Artifact.zip压缩包,将Artifact工程导入常用的开发工具即可。

2、使用开发工具手动构建Spring Boot工程(本文采用Intellij Idea 2016.3)

1、新建一个Maven的web工程

2、在pom.xml文件中添加Spring Boot的相关依赖

添加父级依赖,这样当前的项目就是Spring Boot项目了。spring-boot-starter-parent是一个特殊的starer,它用来提供相关的maven默认依赖,使用它之后,当前项目的的常用依赖包就可以省去version标签。

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

添加spring-boot-starter依赖,spring-boot-starter是Spring Boot核心starter,包含自动配置、日志、yaml配置文件的支持。

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

然后在dependencies中添加Web支持的starter pom。

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

spring-boot-starter-web会自动添加它所依赖的jar包

然后添加Spring Boot的编译插件,便于使用Spring Boot命令操作工程

    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <fork>true</fork>
        </configuration>
    </plugin>

3、简单测试

新建包路径com.gnd.chapter01,在com.gnd.chapter01包路径下新建Chapter01Application.java入口类,编写入口方法

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


@SpringBootApplication是一个组合注解,查看其源码,@SpringBootApplication
组合了@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan三个注解,@SpringBootConfiguration表示当前类是一个启动应用程序的入口;@EnableAutoConfiguration注解开启自动配置,让Spring Boot根据类路径中的jar包依赖为当前项目进行自动配置(例如:添加了spring-boot-starter-web依赖,会自动添加tomcat和SpringMVC的依赖);@ComponentScan会以Application入口类所在目录为根目录,自动扫描工程中标注了@Component注解的类。

然后新建目录controller,在其中新建一个HelloController测试类。

    @RestController
    public class HelloController {
        @RequestMapping("/hello")
        public String index() {
            return "Hello, World!";
        }
    }

@RestController也是一个组合注解,组合了@Controller@ResponseBody两个注解

4、运行

使用Spring Boot命令运行工程,mvn spring-boot:run,或者直接运行Chapter01Application类,在浏览器中访问http://localhost:8080/hello即可访问HelloController。

上一篇 下一篇

猜你喜欢

热点阅读