springboot学习、实战系列项目

三种方法带你新建SpringBoot项目

2020-12-16  本文已影响0人  程序员Mark_Chou

创建的三种方式

结构说明

SpringBoot 的设计目的是简化Spring的搭建与开发,尤其是没有了好多繁琐的配置。本篇文章主要介绍如何搭建SpringBoot项目。

从官网创建

访问Spring的官方网站 https://start.spring.io/,如下:

image-20201216130444068.png

只需要简单的配置几下,

以上配置完成后点击 GENERATE 按钮自动打包下载新建的项目。

IDE创建

开发工具创建项目本质还是通过上述网站创建,只是创建过程由开发工具完成。下面以IDEA为例说明(也可以在Eclipse中通过STS创建)。

依次选择“File->New->Project”,打开 New Project窗口,左侧选择Spring Initializr,右侧勾选Default(这里就能看出IDEA也是通过官网创建)。

image-20201216200702340.png

点击Next填写项目信息。

image-20201216200856962.png

填写的信息也和官网创建方式相同,再点击Next选择要添加的依赖。

image-20201216201204549.png

然后点击Next即可完成项目的创建。

Maven直接创建

首先建一个普通的Maven项目,创建完成后在pom.xml中添加如下依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.3.RELEASE</version>
</parent>

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

之后需要在java目录添加包并创建一个启动类。

package com.chou.easyspringboot.easyspringboothelloworld;

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

@SpringBootApplication
public class MyApplication {

   public static void main(String[] args) {
      SpringApplication.run(MyApplication.class, args);
      System.out.println("Hello World");
   }

}

@SpringBootApplication 等同于同时使用@Configuration, @EnableAutoConfiguration 和 @ComponentScan默认属性的情况。

@Configuration,熟悉Spring的应该都清楚该注解和@Bean搭配使用标识该类是bean的来源,而被@Bean注解标识的方法会返回一个bean,并且该bean会交由Spring容器管理。

@EnableAutoConfiguration是SpringBoot实现自动化配置的核心注解,该注解会将所有符合条件的@Configuration 配置加载到IoC容器中。

@ComponentScan会自动扫描指定包下的标有@Component、@Service、@Repository或@Controller的类,并将其注册成bean。官方建议将@SpringBootApplication注解的类放在根目录下,因为@ComponentScan扫描范围是当前目录及当前目录的子目录,当然也可以通过basePackages属性指定扫描范围。

项目结构
image-20201216205831718.png

java目录存放java代码,resources目录主要存放项目的配置文件、静态资源、web项目里的视图模板等,test是测试目录。

上一篇 下一篇

猜你喜欢

热点阅读