Spring Boot 入门(一):入门案例

Springboot 入门

入门案例

  • 创建spring boot项目
  • 在pom.xml 文件,我们需要添加两部分依赖。
    — 让我们的项目继承spring-boot-starter-parent 的工程
    — 加入spring-boot-starter-web 的依赖
    — spring boot 官网搭建教程 Spring Boot Reference Guide
<!-- Inherit defaults from Spring Boot -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.6.RELEASE</version>
	</parent>
&lt;!-- Add typical dependencies for a web application --&gt;
&lt;dependencies&gt;
	&lt;dependency&gt;
		&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
		&lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
	&lt;/dependency&gt;
&lt;/dependencies&gt;

&lt;!-- Package as an executable jar --&gt;
&lt;build&gt;
	&lt;plugins&gt;
		&lt;plugin&gt;
			&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
			&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
		&lt;/plugin&gt;
	&lt;/plugins&gt;
&lt;/build&gt;

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

— Spring Boot 项目默认的编译版本是1.6,如果我们想使用更高的JDK版本,我们就需要在pom.xml 文件定义一个变量。

<!--定义变量 -->
<properties>
    <java.version>1.8</java.version>
</properties>

  
  
  • 1
  • 2
  • 3
  • 4
  • 创建Spring Boot 启动类
    — 在项目中创建包cn.org.july.springboot.controller
    — 创建HelloController
package cn.org.july.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**

  • @authorwanghongjie
    • 2018-10-26*
  • /
    @Controller
    public class HelloController {
    @RequestMapping(value = “/hello”)
    @ResponseBody
    public String hello(){
    return “hello spring boot…”;
    }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

— 创建项目启动类
在相同包路径下或上层包创建Application.class类,并添加新注解
::@SpringBootApplication::。
Spring Boot启动以main方法进行启动,内部提供::SpringApplication.run()::方法。

package cn.org.july.springboot.controller;

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
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

项目启动后,在浏览器访问127.0.0.1:8080/hello

第二种启动方式

  • 将项目打成jar包方式。
  • 项目通过maven构建,运行mvn install 将项目打包。
  • 打包后路径 target 中,通过 命令java -jar XXX.jar 启动
  • 访问 127.0.0.1:8080/hello
    #springboot/入门案例

猜你喜欢

转载自blog.csdn.net/wangliang369/article/details/83477175
今日推荐