最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot讀取配置的6種方式

 更新時間:2023年08月25日 11:59:30   作者:白豆五  
本文主要介紹了SpringBoot讀取配置的6種方式,主要包括使用默認配置、使用application.properties文件、使用application.yml文件、使用@Value注解、使用Environment對象和使用ConfigurableEnvironment對象,感興趣的可以了解一下

1. 概述

通過了解springboot加載配置,可以更方便地封裝自定義Starter。

在SpringBoot中,可以使用以下6種方式讀取 yml、properties配置:

  • 使用@Value注解:讀取springboot全局配置文件單個配置。
  • 使用Environment接口:通過Environment接口動態(tài)獲取配置。(將yml全部數(shù)據(jù)封裝到Environment對象)
  • 使用@ConfigurationProperties注解:在配置類上使用@ConfigurationProperties注解并指定加載配置項的前綴,就可以批量讀取配置注入自定義類的成員變量中。(自定義類需要提供setter方法)
  • 使用PropertySource注解:加載properties文件配置,然后在字段上使用@Value獲取配置。
  • 配置PropertySourcesPlaceholderConfigurer的Bean加載自定義yml文件,然后在字段上使用@Value獲取配置。
  • Java原生方式獲取配置。(IO流)

環(huán)境準(zhǔn)備:

1、創(chuàng)建maven項目(不需要任何archetype模板構(gòu)建)

2、引入依賴:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>cn.aopmin</groupId>
    <artifactId>springboot-loadconfig</artifactId>
    <version>1.0.0</version>
    <!--父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <!-- SpringBoot配置元數(shù)據(jù)的注解處理器,可以讓自定義配置實現(xiàn)自動補全和校驗功能 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- web起步依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- junit -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

3、編寫啟動類:

package cn.aopmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LoadConfigApplication {
    public static void main(String[] args) {
        SpringApplication.run(LoadConfigApplication.class, args);
    }
}

2. 使用@Value注解讀取單個配置

1、編寫application.yml文件配置:

student:
  name: jack
  age: 20

2、使用@Value讀取配置:

@SpringBootTest
@Slf4j
public class ValueTest {
    @Value("${student.name}")
    private String name;
    @Value("${student.age}")
    private Integer age;
    @Test
    public void test() {
    log.info("@Value 配置獲取 name:{},age:{}",name,age);
    }
}

@Value注意事項:

@Value 注解只能讀取單個配置進行賦值,無法讀取整個配置文件批量賦值。當(dāng)使用@Value注解讀取配置時,確保配置在yml中存在,否則啟動程序時就會報錯。注解中屬性名引用方式如下:

@Value("${一級屬性名.二級屬性名...}")

② 當(dāng)使用 @Value 注解引用屬性時,可以在屬性名稱后面使用冒號(: default-value )的形式添加默認值。這樣,如果在配置文件中找不到對應(yīng)的屬性,就會使用默認值。如果在配置文件中找到了屬性,其值將會覆蓋默認值。

//可以使用各種類型的默認值,包括字符串、數(shù)字、布爾值等
@Value("${student.name:aopmin}")
private String name;
@Value("${student.age:18}")
private Integer age;
//表示一個空字符串作為默認值
@Value("${student.name:}")
private String name;

@Value 注解只能用于被Spring管理的Bean中使用,,如使用 @Component @Service @Controller 等注解修飾的類,或者使用Java配置編寫的 @Configuration 類中。

@Value 注解可以用于字段、構(gòu)造函數(shù)參數(shù)、方法參數(shù)和方法上。當(dāng)將它放在方法上時,Spring容器初始化時會調(diào)用該方法,并將配置屬性的值作為方法的參數(shù)傳遞進去。

@Component
public class MyBean {
    private String myProperty;
    @Autowired
    public MyBean(@Value("${my.property}") String myProperty) {
        this.myProperty = myProperty;
    }
    @Value("${another.property}")
    public void setAnotherProperty(String anotherProperty) {
        // do something with anotherProperty...
    }
    @Value("${yet.another.property}")
    public void processValue(String value) {
        // do something with value...
    }
}
/*
@Value注解被用于構(gòu)造函數(shù)參數(shù)、setter方法和普通方法上。容器初始化時,會將配置屬性的值作為參數(shù)傳遞到構(gòu)造函數(shù)、setter方法和普通方法中。
*/

@Value 注解不能在 static 修飾的字段上使用。因為@Value注解是通過訪問Spring容器中的上下文來解析屬性值并注入到目標(biāo)字段中的。由于static字段不屬于對象實例,無法通過實例訪問容器,所以在靜態(tài)字段上使用@Value注解是無效的。

3. 使用@ConfigurationProperties注解批量綁定

1、編寫application.yml文件配置:

student:
  name: jack
  age: 20

2、使用@ConfigurationProperties批量綁定:

package cn.aopmin.pojo;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
 * 參數(shù)配置類   (需要提供setter方法)
 *
 * @author 白豆五
 * @version 2023/07/16
 * @since JDK8
 */
@Component
@Data
//將這個類與配置文件前綴為student的配置綁定,然后把yml、properties中關(guān)于student的配置信息注入到當(dāng)前類的成員變量中
@ConfigurationProperties(prefix = "student")
public class StudentProperties {
    private String name;
}

3、測試

@SpringBootTest
public class ConfigurationPropertiesTest {
    @Autowired
    private StudentProperties studentProperties;
    @Test
    public void test() {
        System.out.println("讀取配置: name==="+studentProperties.getName());
    }
}

@ConfigurationProperties注意事項:

  • 確保添加了@EnableConfigurationProperties注解:為了使@ConfigurationProperties生效,需要在主配置類上添加@EnableConfigurationProperties(value=xxxxProperties.class)注解,開啟@ConfigurationProperties注解自動裝配功能。
  • 配置文件中的屬性名與類字段名的映射規(guī)則:默認情況下,@ConfigurationProperties會將配置文件中的屬性名與類字段名進行映射。例如,配置文件中的屬性student.name會自動映射到類字段name上。如果配置文件中的屬性名與類字段名不一致,可以使用@Value注解或通過setter方法來指定映射關(guān)系。
  • 類必須是Spring管理的Bean:被@ConfigurationProperties注解標(biāo)記的類必須是由Spring容器管理的Bean,因此需要確保該類被@Component或其他相關(guān)注解標(biāo)記,以便Spring能夠掃描并創(chuàng)建該類的實例。
  • 支持類型轉(zhuǎn)換:@ConfigurationProperties支持自動類型轉(zhuǎn)換,將配置文件中的字符串值轉(zhuǎn)換為目標(biāo)字段的類型。例如,將字符串轉(zhuǎn)換為整數(shù)、布爾值等。如果無法進行類型轉(zhuǎn)換,會拋出異常。
  • 默認值和可選屬性:可以為@ConfigurationProperties注解的字段設(shè)置默認值,以防止配置文件中缺少對應(yīng)的屬性。可以使用":“符號指定默認值,例如@Value(”${my.property:default-value}")。另外,可以使用required屬性來指定某個屬性是否為必需的。
  • 配置項的驗證和校驗:可以使用JSR-303/349規(guī)范的注解對@ConfigurationProperties注解的字段進行驗證和校驗。例如,使用@NotBlank、@Min、@Max等注解來限制屬性值的有效性。

4. 使用Environment動態(tài)獲取配置

1、編寫application.yml文件配置:

student:
  name: jack
  age: 20

2、使用Environment動態(tài)獲取配置:(將Environment對象自動裝配,然后調(diào)用getProperty()方法獲取指定屬性值)

package cn.aopmin.test;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import javax.annotation.Resource;
/**
 * Environment是springboot核心的環(huán)境配置接口,它提供了一些方法用于訪問應(yīng)用程序配置屬性。
 * 包括系統(tǒng)屬性、操作系統(tǒng)環(huán)境變量、命令行參數(shù)、以及配置文件中定義的屬性等等
 *
 * @author 白豆五
 * @version 2023/07/16
 * @since JDK8
 */
@Slf4j
@SpringBootTest
public class EnvironmentTest {
    @Resource
    private Environment env;
    @Test
    public void test() {
        String name = env.getProperty("student.name");
        // 邏輯處理...(也可以控制某一個bean是否生效)
        log.info("Environment配置讀取: name:{}", name);
    }}

除了自動裝配方式,也可以從spring容器中獲取bean:

@Slf4j
@SpringBootTest
public class EnvironmentTest2 implements EnvironmentAware {
    private Environment env;
    @Test
    public void test() {
        String name = env.getProperty("student.name");
        log.info("Environment配置讀取: name:{}", name);
    }
    @Override
    public void setEnvironment(Environment environment) {
        // 邏輯處理...(也可以控制某一個bean是否生效)
        this.env = environment;
    }
}

Aware是Spring框架提供的一組特殊接口,可以讓Bean從Spring容器中拿到一些資源信息。

Aware接口是一種回調(diào)機制,當(dāng)Bean被實例化并注冊到Spring容器中時,容器會自動調(diào)用Bean中實現(xiàn)了特定Aware接口的方法,將相應(yīng)的資源或信息傳遞給Bean。

以下是幾個常用的Aware接口:

  • ApplicationContextAware:通過實現(xiàn)該接口,Bean可以訪問ApplicationContext對象,從而獲取Spring容器的相關(guān)信息。
  • BeanFactoryAware:通過實現(xiàn)該接口,Bean可以訪問BeanFactory對象,從而獲取Bean在容器中的相關(guān)信息。
  • EnvironmentAware:通過實現(xiàn)該接口,Bean可以訪問Environment對象,從而獲取環(huán)境相關(guān)的配置屬性,比如系統(tǒng)屬性、環(huán)境變量等。
  • ResourceLoaderAware:通過實現(xiàn)該接口,Bean可以訪問ResourceLoader對象,從而獲取資源加載器,用于加載類路徑下的資源文件。
  • MessageSourceAware:通過實現(xiàn)該接口,Bean可以訪問MessageSource對象,從而獲取國際化消息。

5.使用@PropertySources注解獲取外部配置

前3種都是從springboot全局配置文件中獲取配置,如果獲取外部自定義文件就不可以啦,我們可以通過@PropertySources注解獲取==.properties==文件配置。

1、在resources目錄下創(chuàng)建student.properties文件:

student.id=1001
student.name=白豆五

2、在配置類中使用@PropertySources注解綁定配置:

package cn.aopmin.pojo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
 * 綁定自定義properties配置
 *
 * @author 白豆五
 * @version 2023/07/16
 * @since JDK8
 */
@Data
@Configuration
@PropertySource(value = "classpath:student.properties", encoding = "UTF-8")
public class PropertySourcesConf {
    @Value("${student.id}")
    private Integer id;
    @Value("${student.name}")
    private String name;
}

3、測試

@SpringBootTest
@Slf4j
public class PropertySourcesTest {
    @Resource
    private PropertySourcesConf propertySourcesConf;
    @Test
    public void test() {
       log.info("PropertySources配置讀取 id: {}", propertySourcesConf.getId());
            log.info("name: {}", propertySourcesConf.getName());
    }
}

6. 配置PropertySourcesPlaceholderConfigurer的Bean獲取外部配置

1、編寫student.yml配置:

file:
  type: 自定義yaml文件配置

2、 配置PropertySourcesPlaceholderConfigurer獲取自定義yml文件配置:

package cn.aopmin.config;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import java.util.Objects;
/**
 * 配置PropertySourcesPlaceholderConfigurer讀取yml配置
 * @author 白豆五
 * @version 2023/07/16
 * @since JDK8
 */
@Configuration
public class MyYamlConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer yamlConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("student.yml"));//自定義yml文件
        //Objects.requireNonNull()方法的作用是如果對象為空,則拋出空指針異常,否則返回對象本身。
        configurer.setProperties(Objects.requireNonNull(yaml.getObject()));
        return configurer;
    }
}

3、測試

@SpringBootTest
public class LoadYamlTest {
    @Value("${file.type}")
    private String fileType;
    @Test
    public void test() {
        System.out.println("讀取yaml配置:"+fileType);
    }
}

7. Java原生方式獲取配置

通過IO流讀取配置,然后放入propertis配置對象中。

package cn.aopmin.test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
/**
 * @author 白豆五
 * @version 2023/07/16
 * @since JDK8
 */
@SpringBootTest
public class CustomTest {
    @Test
    public void test() {
        // 配置對象
        Properties props = new Properties();
        InputStreamReader input = null;
        try {
            // 輸入流 (字節(jié)流轉(zhuǎn)字符流)
            input = new InputStreamReader(
                    this.getClass().getClassLoader().getResourceAsStream("student.properties"),//通過類加載器來獲取指定路徑下的資源文件,并返回一個InputStream對象
                    StandardCharsets.UTF_8); //指定編碼格式
            // 加載配置
            props.load(input);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (input!=null)
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        // 獲取配置
        System.out.println("id:" + props.getProperty("student.id") + ", name:" + props.getProperty("student.name"));
    }
}

到此這篇關(guān)于SpringBoot讀取配置的6種方式的文章就介紹到這了,更多相關(guān)SpringBoot讀取配置 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

  • Java通俗易懂系列設(shè)計模式之適配器模式

    Java通俗易懂系列設(shè)計模式之適配器模式

    這篇文章主要介紹了Java通俗易懂系列設(shè)計模式之適配器模式,對設(shè)計模式感興趣的同學(xué),一定要看一下
    2021-04-04
  • Mybatis入門教程之新增、更新、刪除功能

    Mybatis入門教程之新增、更新、刪除功能

    這篇文章給大家介紹了Mybatis進行基本的增刪改操作,非常不錯,具有參考借鑒價值,需要的的朋友參考下
    2017-02-02
  • Java讀取制表符文本轉(zhuǎn)換為JSON實現(xiàn)實例

    Java讀取制表符文本轉(zhuǎn)換為JSON實現(xiàn)實例

    在Java開發(fā)中,處理各種數(shù)據(jù)格式是常見的任務(wù),本文將介紹如何使用Java讀取制表符文本文件,并將其轉(zhuǎn)換為JSON格式,以便于后續(xù)的數(shù)據(jù)處理和分析,我們將使用Java中的相關(guān)庫來實現(xiàn)這個過程,并提供詳細的代碼示例
    2024-01-01
  • 淺談Java中的分布式鎖

    淺談Java中的分布式鎖

    這篇文章主要介紹了淺談Java中的分布式鎖,為了保證一個方法或?qū)傩栽诟卟l(fā)情況下的同一時間只能被同一個線程執(zhí)行,在傳統(tǒng)單體應(yīng)用單機部署的情況下,可以使用Java并發(fā)處理相關(guān)的API(如ReentrantLock或Synchronized)進行互斥控制,需要的朋友可以參考下
    2023-09-09
  • Java泛型機制必要性及原理解析

    Java泛型機制必要性及原理解析

    這篇文章主要介紹了Java泛型機制必要性及原理解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-05-05
  • Log4j不同模塊輸出到不同的文件中

    Log4j不同模塊輸出到不同的文件中

    這篇文章主要介紹了Log4j不同模塊輸出到不同的文件中 的相關(guān)資料,需要的朋友可以參考下
    2016-08-08
  • java maven項目如何讀取配置文件信息

    java maven項目如何讀取配置文件信息

    這篇文章主要介紹了java maven項目如何讀取配置文件信息,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • MyBatis-Plus聯(lián)表查詢(Mybatis-Plus-Join)的功能實現(xiàn)

    MyBatis-Plus聯(lián)表查詢(Mybatis-Plus-Join)的功能實現(xiàn)

    mybatis-plus作為mybatis的增強工具,簡化了開發(fā)中的數(shù)據(jù)庫操作,這篇文章主要介紹了MyBatis-Plus聯(lián)表查詢(Mybatis-Plus-Join),需要的朋友可以參考下
    2022-08-08
  • Java生產(chǎn)者和消費者實現(xiàn)等待喚醒機制

    Java生產(chǎn)者和消費者實現(xiàn)等待喚醒機制

    本文主要介紹了Java生產(chǎn)者和消費者實現(xiàn)等待喚醒機制,通過synchronized、wait()和notifyAll()實現(xiàn)線程間的安全協(xié)作,具有一定的參考價值,感興趣的可以了解一下
    2025-06-06
  • 詳解spring cloud hystrix緩存功能的使用

    詳解spring cloud hystrix緩存功能的使用

    這篇文章主要介紹了詳解spring cloudhystrix緩存功能的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-08-08

最新評論

新干县| 上思县| 横山县| 吐鲁番市| 西城区| 阿坝县| 中卫市| 建水县| 邳州市| 会宁县| 灵山县| 宁明县| 平陆县| 建湖县| 东光县| 新建县| 商都县| 措勤县| 峡江县| 神池县| 红桥区| 闸北区| 白城市| 铁岭县| 墨竹工卡县| 龙陵县| 西畴县| 津市市| 巨野县| 锡林浩特市| 体育| 罗定市| 突泉县| 合作市| 新乡市| 海晏县| 陆川县| 康马县| 云阳县| 武宣县| 洛隆县|