Skip to content

springboot的使用方式

一、引入依赖


    <parent>
        <!--spring boot依赖包-->
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.4</version>
    </parent>

    <dependencies>

    <dependencies>
        <!-- springboot关联依赖 start -->
        <!--springboot基础依赖-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
        </dependency>
        <!--springboot web依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!--json依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-json</artifactId>
        </dependency>
    </dependencies>

二、配置文件

#不配置默认8080
server:
  port: 11005
spring:
  freemarker:
    cache: false    #页面不加载缓存,修改即时生效
  servlet:
    multipart:
      enabled: true
      file-size-threshold: 0
      max-file-size:  10240 #单个数据的大小
      max-request-size: 10240 #总数据的大小
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss

三、启动类

/**
 * @Description 启动类
 * @Author lcy
 * @Date 2021/4/12 17:09
 */
@SpringBootApplication
@ComponentScan(basePackages = "com.lcy.study")
public class ProjectApplication {

    public static void main(String[] args){
        SpringApplication.run(ProjectApplication.class,args);
    }

}

四、获取application配置文件

  1. 正常获取通过@Value("${属性名}") 获取

  2. 通过Environment类

ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
       Environment environment = context.getBean(Environment.class);
       String property = environment.getProperty("属性名");
        System.out.println(property);

配置文件信息:搜索文件spring-configuration-metadata.json,里面有相关application的配置文件信息

五、多环境配置

#springboot多环境配置,定义的文件名一定是application-***的形式,***表示的是profile名
#指定哪个profile,比如现在指定的配置文件是application-dev
spring:
  profiles:
   active: dev

六、测试类启动

增加两个注解,在测试的时候启动springboot的服务。2.4引入junit5移除了@RunWith注解

2.4以前

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ProjectApplication.class)