Springboot学习(一)入门和快速创建SpringBoot项目

本文详细介绍了如何从创建SpringBoot项目开始,包括Maven配置、主程序类的编写、依赖管理和SpringApplication的使用,一步步引导读者完成HelloWorld应用的搭建与启动过程,以及核心配置注解的解析。
摘要由CSDN通过智能技术生成

Springboot学习(一) 入门helloworld

创建一个springboot项目

  1. 创建maven项目

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GRJZ3LZ2-1657557476299)(C:\Users\Wang\AppData\Roaming\Typora\typora-user-images\1657552659767.png)]
在这里插入图片描述
2. 引入springboot相关依赖

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.caesar</groupId>
    <artifactId>boot</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
    </properties>

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

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>
  1. 编写主程序类,启动springboot应用
package com.caesar.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// @SpringBootApplication 标注一个主程序类,说明这是一个Spring Boot应用
@SpringBootApplication
public class HelloWorldApplication {
    public static void main(String[] args) {
        // Spring应用启动起来
        SpringApplication.run(HelloWorldApplication.class, args);
    }
}
  1. 编写业务代码(controller、service…)
package com.caesar.boot.controller;

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

@Controller
public class HelloController {

    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {
        return "Hello Spring Boot!";
    }
}
  1. 启动主程序
 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.7.RELEASE)

2022-07-11 23:15:19.629  INFO 8340 --- [           main] com.caesar.boot.HelloWorldApplication    : Starting HelloWorldApplication on DESKTOP-KGBUVDU with PID 8340 (D:\learn\spring-boot-lean\codes\sping-boot-01-helloworld\target\classes started by Wang in D:\learn\spring-boot-lean\codes\sping-boot-01-helloworld)
2022-07-11 23:15:19.631  INFO 8340 --- [           main] com.caesar.boot.HelloWorldApplication    : No active profile set, falling back to default profiles: default
2022-07-11 23:15:21.929  INFO 8340 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-07-11 23:15:21.946  INFO 8340 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-07-11 23:15:21.946  INFO 8340 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.41]
2022-07-11 23:15:22.095  INFO 8340 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-07-11 23:15:22.095  INFO 8340 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2353 ms
2022-07-11 23:15:22.393  INFO 8340 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2022-07-11 23:15:22.706  INFO 8340 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-07-11 23:15:22.723  INFO 8340 --- [           main] com.caesar.boot.HelloWorldApplication    : Started HelloWorldApplication in 3.963 seconds (JVM running for 7.257)
2022-07-11 23:15:36.101  INFO 8340 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-07-11 23:15:36.102  INFO 8340 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-07-11 23:15:36.110  INFO 8340 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 7 ms

  1. 启动成功后,在浏览器中访问http://localhost:8080/hello

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UxePHJ6S-1657557476301)(C:\Users\Wang\AppData\Roaming\Typora\typora-user-images\1657553270144.png)]

  1. 打包,引入Spring Boot打包插件,将应用打成jar包,使用java -jar xxx.jar命令,执行jar包
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>${spring-boot.version}</version>
        </plugin>
    </plugins>
</build>

分析Hello World pom

版本仲裁中心

管理Spring Boot中所有的依赖版本

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

场景启动器

spring-boot-starter-xxx: 场景启动器

Spring Boot将所有的功能场景都抽取出来,作用starter(启动器)。只需要在项目中引入starter,相关场景的所有依赖都会导入进来

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

spring-boot-starter-web: web场景启动器;导入web模块正常运行所依赖的组件。

主程序类

Spring Boot 应用的启动类

// 标注一个主程序类,说明这是一个Spring Boot应用
@SpringBootApplication
public class HelloWorldApplication {
    public static void main(String[] args) {
        // Spring应用启动起来
        SpringApplication.run(HelloWorldApplication.class, args);
    }
}

@SpringBootApplication

@SpringBootApplication:Spring Boot应用。该注解标注在某个类上,说明该类是SpringBoot的主配置类,SpringBoot就应该运行这个类的main方法来启动SpringBoot应用。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {...}
  1. @SpringBootConfiguration:SpringBoot的配置类;

@SpringBootConfiguration标注在某个类上,表示该类是一个SpringBoot的配置类;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {...}
  • @Configuration:配置类来标注该注解。等同于配置文件。

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Component
    public @interface Configuration {...}
    
    • @Component:组件;配置类也是容器中的一个组件
  1. @EnableAutoConfiguration:开启自动配置功能。
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {...}
  • @AutoConfigurationPackage:自动配置包

    @Import({Registrar.class})
    public @interface AutoConfigurationPackage {...}
    
    • @Import({Registrar.class}):给容器导入一个组件;导入的组件由@Import({Registrar.class})决定
      • 将主配置类的所在包及以下所有子包中的所有组件扫描到Spring容器中
  • @Import({AutoConfigurationImportSelector.class}):导入组件选择器;将所有需要导入的组件以全类名的方式导入,将组件添加到容器中。会给容器中导入自动配置类(xxxAutoConfiguration),给容器中导入场景需要的所有组件,并配置好。

    • SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
    • SpringBoot应用启动时,从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration指定的值,将获取到的值作为自动配置类导入到容器中,让自动配置类生效。

使用向导(Spring Initialize)快速创建SpringBoot项目(IDEA)

首先创建一个项目,New Project…上图吧
在这里插入图片描述

选择Spring Initialize,这里有Default和Custom两种选择

  • Default:使用Spring官网的快速创建
  • Custom:自定义,一般使用阿里云的 https://start.aliyun.com/

如果网速好的,用哪个都无所谓。但是如果网速差的,就建议使用阿里云的,国内的速度更快。一定要连上网,不然无法使用
在这里插入图片描述
填写好相关的信息
在这里插入图片描述
选择需要的启动器
在这里插入图片描述
最后填写项目名等待完成
在这里插入图片描述

就会创建一个完善的Spring Boot应用

SpringBoot应用默认结构

  • xxxApplication.java :主程序类,标注有@SrpingBootApplication的类

  • resources :资源文件夹

    • static :静态资源文件夹
    • templates :模板文件夹,SpringBoot应用默认jar包使用嵌入式Tomcat,默认不支持JSP页面,可以使用模板引擎(freemarker、thymeleaf等)
    • application.properties :SpringBoot的配置文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值