springboot-配置文件

luckyFang 2021年10月08日 21次浏览

什么是配置文件

配置文件就是包含配置的文件(哈哈哈哈废话文学),比如说mysql链接地址,线程池最大线程数,总而言之就是记录一些可能会用到的配置文件。

springboot的配置文件

springboot支持两种配置文件

  • properties
  • yaml 墙裂推荐

为什么选择压妹儿

server:
	port: 8080

因为采用树状结构,一目了然

注意:

  • key的冒号后面一定要跟一个空格,例如port: 8080
  • yaml格式不支持使用注解@PropertySource注解
  • yaml配置文件结尾是.yml

application.yml

  1. 在resource目录下新建application.yml文件
    image.png
# 修改项目启动端口
server:
  port: 8081
  servlet:
    session:
      timeout: 30
  tomcat:
    uri-encoding: UTF-8

# 自定义配置信息
authorInfo:
  name: "fangfang"
  age: 22
  addr: "Shan Xi Lin Fen"

解释说明:

  1. server 定义服务器配置
  2. port: 定义访问端口
  3. timeout: 30 定义session超时时间30s
  4. uri-encoding: 定义tomcat的uri编码是UTF-8

读取配置信息

通过 @value("${}")来读取配置信息

package com.lu.springboot.bootdemo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class BootDemoApplicationTests {

    @Value("${authorInfo.name}")
    private String name;
    @Value("${authorInfo.age}")
    private int age;
    @Value("${authorInfo.addr}")
    private String addr;


    @Test
    void contextLoads() {
        System.out.println(String.format("我叫%s,我来自%s,今年%d岁了!",name,addr,age));
    }


}

说明:

  1. @SpringBootTest 表示是一个springboot的测试类
  2. @Test 表示是一个测试方法
  3. @Value 获取配置信息

用类装载配置信息

方式1直接装载

  1. 新建一个配置配置类

  2. 设置类信息

package com.lu.springboot.bootdemo.entity;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "author-info")
public class AuthorInfoProperties {
    private String name;
    private String addr;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String add) {
        this.addr = add;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

说明:

  • @Component 标注这是一个组件类
  • @ConfigurationProperties 表示从配置信息读取,自动封装成一个实体类

image.png

发现报错,需要添加依赖

  1. 添加maven依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-configuration-processor</artifactId>
	<version>2.5.5</version>
</dependency>
  1. 测试使用
package com.lu.springboot.bootdemo;

import com.lu.springboot.bootdemo.entity.AuthorInfoProperties;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Optional;

@SpringBootTest
public class PropertiesTest {
    // 自动装配
    @Autowired
    AuthorInfoProperties authorInfoProperties;

    @Test
    void contextLoads(){
        Optional.ofNullable(authorInfoProperties).ifPresent(info -> {
            System.out.println(info.getName());
            System.out.println(info.getAddr());
            System.out.println(info.getAge());
        });
    }
}

fangfang
Shan Xi Lin Fen
22

方式2 @Bean加载方式

package com.lu.springboot.bootdemo.entity;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class PropertiesConfiguration {
    @Bean
    @ConfigurationProperties(prefix = "author-info")
    public AuthorInfoProperties getAuthorInfoProperties(){
        return new AuthorInfoProperties();
    }
}

使用和方式1一样这里就不做详细概述了

application.properties

虽然properties用的不多,但是我们也有必要了解如何使用

author-info.addr="Shan Xi Lin Fen"
author-info.age=22
author-info.name="fang fang"

读取过程和上面相同

多环境配置

  • application-dev.yml测试环境配置文件
  • application-prod.yml生产环境配置文件
  • application.yml主配置文件

application-dev.yml

# 开发环境配置文件


server:
  port: 8080
  

application-prod.yml

# 生产环境配置文件
server:
  port: 8090

application.yml

# 主配置文件

# 采用开发环境
spring:
  profiles:
    active: dev
    # 采用生产环境
#    active: prod
  • 通过 spring.profiles.avtive 来选择环境
  • 或者启动时配置 java -jar --spring.profiles.active=dev

springboot的starter

springboot 提供了很多开箱即用的starter.按需调用

spring-boot-starterCore starter, including auto-configuration support, logging and YAML
spring-boot-starter-activemqStarter for JMS messaging using Apache ActiveMQ
spring-boot-starter-amqpStarter for using Spring AMQP and Rabbit MQ
spring-boot-starter-aopStarter for aspect-oriented programming with Spring AOP and AspectJ
spring-boot-starter-artemisStarter for JMS messaging using Apache Artemis
spring-boot-starter-batchStarter for using Spring Batch
spring-boot-starter-cacheStarter for using Spring Framework’s caching support
spring-boot-starter-data-cassandraStarter for using Cassandra distributed database and Spring Data Cassandra
spring-boot-starter-data-cassandra-reactiveStarter for using Cassandra distributed database and Spring Data Cassandra Reactive
spring-boot-starter-data-couchbaseStarter for using Couchbase document-oriented database and Spring Data Couchbase
spring-boot-starter-data-couchbase-reactiveStarter for using Couchbase document-oriented database and Spring Data Couchbase Reactive
spring-boot-starter-data-elasticsearchStarter for using Elasticsearch search and analytics engine and Spring Data Elasticsearch
spring-boot-starter-data-jdbcStarter for using Spring Data JDBC
spring-boot-starter-data-jpaStarter for using Spring Data JPA with Hibernate
spring-boot-starter-data-ldapStarter for using Spring Data LDAP
spring-boot-starter-data-mongodbStarter for using MongoDB document-oriented database and Spring Data MongoDB
spring-boot-starter-data-mongodb-reactiveStarter for using MongoDB document-oriented database and Spring Data MongoDB Reactive
spring-boot-starter-data-neo4jStarter for using Neo4j graph database and Spring Data Neo4j
spring-boot-starter-data-r2dbcStarter for using Spring Data R2DBC
spring-boot-starter-data-redisStarter for using Redis key-value data store with Spring Data Redis and the Lettuce client
spring-boot-starter-data-redis-reactiveStarter for using Redis key-value data store with Spring Data Redis reactive and the Lettuce client
spring-boot-starter-data-restStarter for exposing Spring Data repositories over REST using Spring Data REST
spring-boot-starter-data-solrStarter for using the Apache Solr search platform with Spring Data Solr
spring-boot-starter-freemarkerStarter for building MVC web applications using FreeMarker views
spring-boot-starter-groovy-templatesStarter for building MVC web applications using Groovy Templates views
spring-boot-starter-hateoasStarter for building hypermedia-based RESTful web application with Spring MVC and Spring HATEOAS
spring-boot-starter-integrationStarter for using Spring Integration
spring-boot-starter-jdbcStarter for using JDBC with the HikariCP connection pool
spring-boot-starter-jerseyStarter for building RESTful web applications using JAX-RS and Jersey. An alternative to spring-boot-starter-web
spring-boot-starter-jooqStarter for using jOOQ to access SQL databases. An alternative to spring-boot-starter-data-jpa or spring-boot-starter-jdbc
spring-boot-starter-jsonStarter for reading and writing json
spring-boot-starter-jta-atomikosStarter for JTA transactions using Atomikos
spring-boot-starter-jta-bitronixStarter for JTA transactions using Bitronix. Deprecated since 2.3.0
spring-boot-starter-mailStarter for using Java Mail and Spring Framework’s email sending support
spring-boot-starter-mustacheStarter for building web applications using Mustache views
spring-boot-starter-oauth2-clientStarter for using Spring Security’s OAuth2/OpenID Connect client features
spring-boot-starter-oauth2-resource-serverStarter for using Spring Security’s OAuth2 resource server features
spring-boot-starter-quartzStarter for using the Quartz scheduler
spring-boot-starter-rsocketStarter for building RSocket clients and servers
spring-boot-starter-securityStarter for using Spring Security
spring-boot-starter-testStarter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito
spring-boot-starter-thymeleafStarter for building MVC web applications using Thymeleaf views
spring-boot-starter-validationStarter for using Java Bean Validation with Hibernate Validator
spring-boot-starter-webStarter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container
spring-boot-starter-web-servicesStarter for using Spring Web Services
spring-boot-starter-webfluxStarter for building WebFlux applications using Spring Framework’s Reactive Web support
spring-boot-starter-websocket

使用starter

假设使用websocket
添加maven依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>2.5.5</version>
</dependency>

然后使用即可