Spring Boot入门(一)- Gradle构建应用

本文介绍SpringBoot的基本使用方法,包括项目构建、配置及RESTful API的实现方式。通过示例展示了如何快速搭建SpringBoot项目,并配置基本的Web环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载自:http://blog.youkuaiyun.com/u013360850/article/details/53415005
              http://blog.youkuaiyun.com/hguisu/article/details/50956370

        Spring Boot提供了一个强大的一键式Spring的集成开发环境,能够单独进行一个Spring应用的开发,其中:
         (1)集中式配置(application.properties)+注解,大大简化了开发流程
         (2)内嵌的Tomcat和Jetty容器,可直接打成jar包启动,无需提供Java war包以及繁琐的Web配置
         (3)提供了Spring各个插件的基于Maven的pom模板配置,开箱即用,便利无比。
         (4)可以在任何你想自动化配置的地方,实现可能
         (5)提供更多的企业级开发特性,如何系统监控,健康诊断,权限控制
         (6)无冗余代码生成和XML强制配置
         (7)提供支持强大的Restfult风格的编码,非常简洁

简单示例

       接下来将采用Gradle来构建简单的SpringBoot项目来逐步学习Spring Boot。首先是配置Gradle脚本,如下:
buildscript {
    repositories {
        mavenLocal()
            mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.0.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'

//生成的jar包包名和版本
ext {
    jarName = project.name
    mainClassName = 'SpringController'
    jarVersion = '0.1.0'
}

jar {
    baseName = jarName
    version = jarVersion
    manifest {
        attributes "Manifest-Version": 1.0, 'Main-Class': mainClassName
    }
}
repositories {
    mavenCentral()
}

//设置jdk的版本
sourceCompatibility = 1.8
targetCompatibility = 1.8

//添加依赖
dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:1.5.0.RELEASE")
    testCompile('org.springframework.boot:spring-boot-starter-test:1.5.0.RELEASE ')
}
       Controller类:
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;


@Controller

//RestController是一种Rest风格的Controller,可以直接返回对象而不返回视图,返回的对象可以使JSON,XML等
//@RestController

//使用自动配置,主动添加并解析bean,配置文件等信息
@EnableAutoConfiguration
public class SpringController {

    //设置访问的url
    @RequestMapping("/")
    //表示返回JSON格式的结果,如果前面使用的是@RestController可以不用写
    @ResponseBody
    String home() {
        return "Hello World!";//返回结果为字符串
    }

    public static void main(String[] args) throws Exception {
        //通过SpringApplication的run()方法启动应用,无需额外的配置其他的文件
        SpringApplication.run(SpringController.class, args);
    }
}
       直接运行main方法,通过浏览器访问访问localhost:8080,就会显示“Hello World!”,表示项目已经运行。或者运行gradle build或者gradle bootRepackage生成可运行jar包,在build/libs下面。

详解Spring Boot

       Spring Boot建议将main方法所在的这个主要的配置类,即SpringController配置在根包名下。那么运行应用后,那么这段代码究竟做了什么呢?从程序的入口SpringApplication.run(SpringController.class, args)开始分析。
       Java代码中没有任何配置,和传统的Spring应用相比,多了个注解@EnableAutoConfiguration,该注解由Spring Boot框架提供。在SpringApplication.run()方法执行后,Spring Boot的autoconfigure发现这是一个Web应用(根据类路径上的依赖确定),于是在内嵌的Tomcat容器中启动了一个Spring的应用上下文,并且监听默认的tcp端口8080。
       同时在Spring Context中根据默认的约定配置了Spring WebMvc。Servlet容器默认的Context路径是/,DispatherServlet匹配的路径(servlet-mapping中的url-patterns)是/*,@ComponentScan路径被默认设置为SampleController的同名package,也就是该package下的所有@Controller,@Service, @Component, @Repository都会被实例化后并加入Spring Context中。
       没有一行配置代码、也没有web.xml。基于Spring Boot的应用在大多数情况下都不需要去显式地声明各类配置,而是将最常用的默认配置作为约定,在不声明的情况下也能适应大多数的开发场景。

       SpringApplication是Spring Boot框架中描述Spring应用的类,它的run()方法会创建一个Spring应用上下文(Application Context)。另一方面它会扫描当前应用类路径上的依赖,例如上例中发现spring-webmvc(由 spring-boot-starter-web传递引入)在类路径中,那么Spring Boot会判断这是一个Web应用,并启动一个内嵌的Servlet容器(默认是Tomcat)用于处理HTTP请求。
       Spring WebMvc框架会将Servlet容器里收到的HTTP请求根据路径分发给对应的@Controller类进行处理,@RestController是一类特殊的@Controller,它的返回值直接作为HTTP Response的Body部分返回给浏览器。@RestController注解是@Controller和@ResponseBody的合集,表示这是个控制器bean,并且是将函数的返回值直接填入HTTP响应体中,是REST风格的控制器。@RequestMapping("/xxx")表示该控制器处理所有“/xxx”的URL请求,具体由那个函数处理,要根据HTTP的方法来区分:GET表示查询、POST表示提交、PUT表示更新、DELETE表示删除。
       @RequestMapping注解表明该方法处理那些URL对应的HTTP请求,也就是常说的URL路由(routing),请求的分发工作是有Spring完成的。例如上面的代码中http://localhost:8080/根路径就被路由至home ()方法进行处理。如果访问http://localhost:8080/hello,则会出现404 Not Found错误,因为并没有编写任何方法来处理/hello请求。

       启动Spring Boot项目最简单的方法就是执行下面的方法:
SpringApplication.run(SpringController.class, args)
       该方法返回一个ApplicationContext对象,使用注解的时候返回的具体类型是AnnotationConfigApplicationContext或AnnotationConfigEmbeddedWebApplicationContext,当支持web的时候是第二个。除了上面这种方法外,还可以用下面的方法:
SpringApplication application = new SpringApplication(SpringController.class);  
application.run(args);  
       SpringApplication包含了一些其他可以配置的方法,如果想做一些配置,可以使用SpringApplicationBuilder:
new SpringApplicationBuilder()  
        .showBanner(false)  
        .sources(SpringController.class)  
        .run(args);  
       当使用SpringMVC的时候由于需要使用子容器,就需要用到SpringApplicationBuilder,该类有一个child(xxx...)方法可以添加子容器。

主要注解

@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注解继承实现)。

@RequestMapping
       注解表明该方法处理那些URL对应的HTTP请求,也就是常说的URL路由(routing),请求的分发工作是有Spring完成的。

项目配置

       Spring Boot最大的特色是“约定优先配置”,大量的默认配置对开发者十分的友好。但是在实际的应用开发过程中,默认配置不可能满足所有场景,同时用户也需要配置一些必须的配置项——例如数据库连接信息。
       Spring Boot的配置系统能够让开发者快速的覆盖默认约定,同时支持Properties配置文件和YAML配置文件两种格式,默认情况下Spring Boot加载类路径上的application.properties或application.yml文件,例如:
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
       YAML格式更加简洁(使用.yml时,属性名的值和冒号中间必须有空格):
spring:
  datasource:
    url: jdbc:mysql://localhost/test
    username: dbuser
    password: dbpass
    driver-class: com.mysql.jdbc.Driver
       一旦发现这些信息,Spring Boot就会根据它们创建DataSource对象。
       另一个常见的配置场景是Web应用服务器:
# Server settings (ServerProperties)
server:
  port: 8080
  address: 127.0.0.1
  sessionTimeout: 30
  contextPath: /


  # Tomcat specifics
  tomcat:
    accessLogEnabled: false
    protocolHeader: x-forwarded-proto
    remoteIpHeader: x-forwarded-for
    basedir:
    backgroundProcessorDelay: 30 # secs
       通过port和address可以修改服务器监听的地址和端口,sessionTimeout配置session过期时间。同时如果在生产环境中使用内嵌Tomcat,当然希望能够配置它的日志、线程池等信息,这些现在都可以通过Spring Boot的属性文件配置,而不再需要再对生产环境中的Tomcat实例进行单独的配置管理了。

Sping boot处理请求

       Spring Boot的URL路由跟SpringMVC一样,不做介绍了,直接看代码:
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestBody;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.RequestParam;  
import org.springframework.web.bind.annotation.RestController;  
  
import com.example.bean.RequestLoginBean;  
import com.example.response.BaseResponse;  
import com.google.gson.Gson;  
  
@RestController  
@RequestMapping(value = "/index")  
public class Login {  
  
    /** 
     * index home 
     *  
     * @return 
     */  
    @RequestMapping(value = "/home")  
    public String home() {  
        return "index home";  
    }  
      
    @RequestMapping(value = "/login", method = RequestMethod.GET)  
    public String loginGet() {  
        return "Login Page";  
    }  
  
    @RequestMapping(value = "/login", method = RequestMethod.POST)  
    public String loginPost() {  
        return "Login Post Request";  
    }  
    /** 
     * 得到1个参数 
     *  
     * @param name 
     *            用户名 
     * @return 返回结果 
     */  
    @GetMapping(value = "/{name}")  
    public String index(@PathVariable String name) {  
        return "oh you are " + name + "<br> nice to meet you";// \n不起作用了,那就直接用html中的标签吧  
    }  
  
    /** 
     * 简单post请求 
     *  
     * @param name 
     * @param pwd 
     * @return 
     */  
    @RequestMapping(value = "/testpost", method = RequestMethod.POST)  
    public String testpost() {  
        System.out.println("hello  test post");  
        return "ok";  
    }  
  
    /** 
     * 简单post的body数据请求 
     *  
     * @param name 
     * @param pwd 
     * @return 
     */  
    @RequestMapping(value = "/testpost", method = RequestMethod.POST)  
    public String testpost2(@RequestBody String dataJson) {  
        System.out.println("hello  test post:" +dataJson);  
        return "ok";  
    }  
    /** 
     * 同时得到两个参数 
     *  
     * @param name 
     *            用户名 
     * @param pwd 
     *            密码 
     * @return 返回结果 
     */  
    @GetMapping(value = "/login/{name}&{pwd}")  
    public String login(@PathVariable String name, @PathVariable String pwd) {  
        if (name.equals("admin") && pwd.equals("admin")) {  
            return "hello welcome admin";  
        } else {  
            return "oh sorry user name or password is wrong";  
        }  
    }  
  
    /** 
     * 通过get请求去登陆 
     *  
     * @param name 
     * @param pwd 
     * @return 
     */  
    @RequestMapping(value = "/loginbyget", method = RequestMethod.GET)  
    public String loginByGet(@RequestParam(value = "name", required = true) String name,  
            @RequestParam(value = "pwd", required = true) String pwd) {  
        return login4Return(name, pwd);  
    }  
  
    /** 
     * 通过post请求去登陆 
     *  
     * @param name 
     * @param pwd 
     * @return 
     */  
    @RequestMapping(value = "/loginbypost", method = RequestMethod.POST)  
    public String loginByPost(@RequestParam(value = "name", required = true) String name,  
            @RequestParam(value = "pwd", required = true) String pwd) {  
        System.out.println("hello post");  
        return login4Return(name, pwd);  
    }  
  
    /** 
     * 参数为一个bean对象.spring会自动为我们关联映射 
     * @param loginBean 
     * @return 
     */  
    @RequestMapping(value = "/loginbypost1", method = { RequestMethod.POST, RequestMethod.GET })  
    public String loginByPost1(RequestLoginBean loginBean) {  
        if (null != loginBean) {  
            return login4Return(loginBean.getName(), loginBean.getPwd());  
        } else {  
            return "error";  
        }  
    }  
      
    /** 
     * 请求内容是一个json串,spring会自动把他和我们的参数bean对应起来,不过要加@RequestBody注解 
     *  
     * @param name 
     * @param pwd 
     * @return 
     */  
    @RequestMapping(value = "/loginbypost2", method = { RequestMethod.POST, RequestMethod.GET })  
    public String loginByPost2(@RequestBody RequestLoginBean loginBean) {  
        if (null != loginBean) {  
            return login4Return(loginBean.getName(), loginBean.getPwd());  
        } else {  
            return "error";  
        }  
    }  
  
      
  
  
    /** 
     * 对登录做出响应处理的方法 
     *  
     * @param name 
     *            用户名 
     * @param pwd 
     *            密码 
     * @return 返回处理结果 
     */  
    private String login4Return(String name, String pwd) {  
        String result;  
        BaseResponse response = new BaseResponse();  
        if (name.equals("admin") && pwd.equals("admin")) {  
            result = "hello welcome admin";  
            response.setState(true);  
        } else {  
            result = "oh sorry user name or password is wrong";  
            response.setState(false);  
        }  
        System.out.println("收到请求,请求结果:" + result);  
        return new Gson().toJson(response);  
    }  
} 
       需要注意的是处理静态文件,为了浏览器能够正确加载类似/css/style.css, /js/main.js等资源。
       默认情况下只需要在src/main/resources/static目录下添加css/style.css和js/main.js文件后,Spring MVC能够自动将他们发布,通过访问/css/style.css, /js/main.js也就可以正确加载这些资源。这些资源经过编译以后是在放在classes\static目录下的。
       也可以在工程的根目录直接建一个 "static"目录(和src同级)。资源都放里面。然后,就能访问了。statis/和 src/main/resources/static目录,如果是同一个静态资源,如check.html. 优先访问src/main/resources/static/check.html。

Production特性
       从前面的例子可以看出,Spring Boot能够非常快速的做出一些原型应用,但是它同样可以被用于生产环境。为了添加生产环境特性支持,需要依赖中引入spring-boot-starter-actuator。加入actuator依赖后,应用启动后会创建一些基于Web的Endpoint:
/autoconfig,用来查看Spring Boot的框架自动配置信息,哪些被自动配置,哪些没有,原因是什么。
/beans,显示应用上下文的Bean列表
/dump,显示线程dump信息
/health,应用健康状况检查
/metrics
/shutdown, 默认没有打开
/trace
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值