SpringBoot笔记 | 一:第一个SpringBoot项目

创建项目

使用idea创建一个SpringBoot项目SpringBoot笔记 | 一:第一个SpringBoot项目_第1张图片
填写项目信息后进入选择依赖界面,可以在此选择项目需要的依赖,暂时选择一个web的依赖
SpringBoot笔记 | 一:第一个SpringBoot项目_第2张图片
点击完成后项目即可创建成功。此时pom文件内容如下


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.5.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.learn.bootgroupId>
    <artifactId>bootdemoartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>bootdemoname>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

Hello World

项目结构如下:
SpringBoot笔记 | 一:第一个SpringBoot项目_第3张图片
创建controller,

@RestController
public class IndexController {

    @RequestMapping("/")
    public String index() {
        return "Hello World!";
    }
}

启动类BootdemoApplication上的注解@SpringBootApplication默认扫描本包及子包的注解,所以@RestController会被扫描到。如果类没在启动类的子包下,可以在启动类上增加@ComponentScan注解自定义扫描路径。

此时启动BootdemoApplication看见如下输出,启动成功
SpringBoot笔记 | 一:第一个SpringBoot项目_第4张图片
项目通过Tomcat启动,默认端口号为8080,contextPath为空,此时访问http://localhost:8080/,即可看见Hello World!

application.properties/application.yml

SpringBoot的主要配置都是通过此配置文件进行配置的,比如我们可以进行如下配置:

#端口号
server.port=8081
server.servlet.context-path=/boot

将项目进行重启,可以看到如下信息
SpringBoot笔记 | 一:第一个SpringBoot项目_第5张图片
此时端口号已经变为8081,contextPath为/boot,再次访问http://localhost:8081/boot/再次看到Hello World!输出。

application.yml

SpringBoot还支持yml格式的配置文件,将application.properties改成application.yml;并将内容修改如下

#端口号
server:
  port: 8081
  servlet:
    context-path: /boot

再次启动项目,访问http://localhost:8081/boot/可获得同样效果。

打包

运行maven命令(跳过测试)

mvn clean package -Dmaven.test.skip=true

可以发现在target目录下会生成bootdemo-0.0.1-SNAPSHOT.jarjar文件,直接cmd到相应目录下,运行命令

java -jar bootdemo-0.0.1-SNAPSHOT.jar

即可启动成功
SpringBoot笔记 | 一:第一个SpringBoot项目_第6张图片
SpringBoot启动时还可以增加命令行参数,优先级比配置文件高,比如:

java -jar bootdemo-0.0.1-SNAPSHOT.jar --server.port=8080

此时启动端口号又会变成8080,在多环境配置是此属性会比较有用。

你可能感兴趣的:(SpringBoot)