SpringBoot+Gradle运行简单Demo Eclipse

来源:互联网 发布:淘宝机箱定制线哪家好 编辑:程序博客网 时间:2024/05/29 03:00

Spring的繁琐的配置简直是每个项目开始的时候都会吐槽的地方,特别是对于较为小型的项目,或者是个人项目,过于繁琐的配置就更显得多余了。Spring
boot是Spring推出的一个轻量化web框架,主要解决了Spring对于小型项目饱受诟病的配置和开发速度问题。
Gradle是一个基于Apache Ant和Apache Maven概念的项目自动化构建工具。它使用一种基于Groovy的特定领域语言(DSL)来声明项目设置,抛弃了基于XML的各种繁琐配置。


综上述:Spring Boot 和 Gradle 组合起来会使我们的开发更简单快捷。


需要开发工具:
Eclipse
Gradle 插件
1.进入官网下载示例代码:
http://start.spring.io/
2.选择Gradle版本、Java开发语言、最新稳定版本、包结构、项目名,下载:
选择Gradle版本、Java开发语言、最新稳定版本、包结构、项目名,下载

3.导入Eclipse中,项目结构如下:
如何导入Gradle项目,请参考:《Eclipse导入Gradle项目》
这里写图片描述

4.在build.gradle中添加Spring Boot的Tomcat插件
compile('org.springframework.boot:spring-boot-starter-web')
完整build.gradle代码如下:

buildscript {    ext {        springBootVersion = '1.5.8.RELEASE'    }    repositories {        mavenCentral()    }    dependencies {        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")    }}apply plugin: 'java'apply plugin: 'eclipse'apply plugin: 'org.springframework.boot'group = 'com.david'version = '0.0.1-SNAPSHOT'sourceCompatibility = 1.8repositories {    mavenCentral()}dependencies {    compile('org.springframework.boot:spring-boot-starter')    compile('org.springframework.boot:spring-boot-starter-web')    testCompile('org.springframework.boot:spring-boot-starter-test')}

5.创建HelloController.java,完整代码如下:

package com.david.translate;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class HelloController {    @RequestMapping("/")    @ResponseBody    public String sayHello(){        return "hello";    }}

6.在TranslateApplication.java中右键运行。TranslateApplication.java命名是在SpringBoot官网填写的项目名+Application.java。默认为DemoApplication.java
TranslateApplication.java中源码如下:

package com.david.translate;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class TranslateApplication {    public static void main(String[] args) {        SpringApplication.run(TranslateApplication.class, args);    }}

注意:这里TranslateApplication.java的类注解为:@SpringBootApplication
这里是最新的1.5.8版本。如果是老版本的话,引入的注解可能为:

@Controller@EnableAutoConfiguration

这里就需要增加注解,用来扫描controller包:

@ComponentScan

或者直接把注解改为:

@SpringBootApplication

还需要注意的是:
新创建的controller文件,必须与启动文件TranslateApplication.java同一级目录或者在TranslateApplication.java的下一层目录:
如:
TranslateApplication.java 在com.test.demo目录下,那么创建新的Controller文件必须在com.test.demo目录下或者com.test.demo.controller。不然访问会提示404.

运行成功:
这里写图片描述
访问(默认的tomcat端口为8080):
这里写图片描述
至此,SpringBoot+Gradle简单Demo运行成功。
如果要改tomcat端口,需要在application.properties中增加如下配置:

server.port=8082

然后重新运行。运行成功结果:
这里写图片描述