SpringBoot学习笔记(创建SpringBoot项目)

SpringBoot学习笔记(创建SpringBoot项目)

创建一个SpringBoot项目;

第一步:创建maven项目;(jar)

1、创建新项目;


2、选择maven项目;


3、填写名字;


4、选择maven自动导入;


5、选择设置;


6、将maven设置为本地配置好的;


第二步、导入SpringBoot相关的依赖;

1、导入依赖;

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

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

3、编写一个主程序;(启动SpringBoot应用)

1、新建HelloWorldMainApplicaiton.java;


2.给HelloWorldMainApplication添加@SpringBootApplication注解:来标注一个主程序类,说明这是一个SpringBoot应用;

package com.cenmingzhong;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author cenmingzhong
 * @SpringBootApplication:来标注一个主程序类,说明这是一个SpringBoot应用
 * @create 2020-10-25-下午 13:07
 */
@SpringBootApplication
public class HelloWorldMainApplication {
          
   

    public static void main(String[] args) {
          
   

        //Spring应用启动起来
        SpringApplication.run(HelloWorldMainApplication.class,args);
    }
}

4、编写相关的Controller、Service;

1、新建HelloController.java;


2.使用@Controller注解来讲HelloController.java加入容器,使用@RequestMapping("/hello")注解来接收来自浏览器的hello请求,使用@ResponseBody注解来将数据返回到浏览器;

package com.cenmingzhong.controller;

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

/**
 * @author cenmingzhong
 * @create 2020-10-25-下午 13:18
 */
@Controller
public class HelloController {
          
   
    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
          
   
        return "Hello World!";
    }
}

5、运行主程序进行测试;

1、在HelloWorldMainApplication.java点击三角形符号,运行项目;


2、可以在控制台看到运行信息,可以看到Tomcat已经启动,8080端口,因为有内嵌Tomcat,所以不需要配置Tomcat;


3、访问localhost:8080/hello,可以正常访问,也正常返回返回值;


6、简化部署

1、导入插件,将应用打包成一个可执行的jar包;

<!--这个插件可以将应用打包成一个可执行的jar包-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

2、在maven中选择命令,在Lifecycle中选择package进行打包;


3、打好的包放在工程目录下target下;


4、把该jar包复制出来放在一个新的文件夹,在导航栏输入cmd,进入控制台;


5、输入java -jar SpringBootTest-1.0-SNAPSHOT.jar命令,执行该jar包,也可以将项目启动起来;


6、访问localhost:8080/hello,可以正常访问,也正常返回返回值;


经验分享 程序员 微信小程序 职场和发展