1. 組態檔
1.1 外部加載順序
-
命令列引數
java -jar spring-boot-02-config-02.0.0.1-SNAPSHOT.jar --server.port=8087 java -jar spring-boot-02-config-02.0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
-
來自java:comp/env的NDI屬性
-
Java系統屬性(System.getProperties() )
-
作業系統環境變數
-
RandomValuePropertySource配置的random.*屬性值
-
jar包外部的
application-{profile}.properties
或application.yml
(帶spring.profile)組態檔-hello |- a.jar |- application.yml
將打好的jar包放在一個目錄下,比如叫做 hello的檔案夾,然后再該檔案夾下新建一個名為application.yml的檔案,其中指定port為8088
,訪問路徑為/boot ,然后命令列直接啟動專案,java -jar a.jar
瀏覽器通過 localhost:8088/boot/hello 可以正常訪問,表示同級目錄下的組態檔生效了, -
jar包內部的application-{profile}.properties或application.yml(帶spring.profile)組態檔
-
jar包外部的application.properties或application.yml(不帶spring.profile)組態檔
-
jar包外部的application.properties或application.yml(不帶spring.profile)組態檔
-
jar包內部的application.properties或application.yml(不帶spring.profile)組態檔
-
@Configuration注解類上的propertySource
-
通過SpringApplication.setDefaultProperties指定的默認屬性,
1.2 springboot內部加載順序
- 組態檔可以放在下面四個地方(優先級依次)
file:./config
:專案根目錄中config下file:./
:專案根目錄下classpath:./config
:專案的resources目錄中config下classpath:./
:專案的resources目錄下
當使用的專案是module級別的時候,必須使用級別是project級別才能掃描到
file:
下面的檔案
- 同目錄下
.properties
的優先級比.yml
高, - 如果同一個配置屬性,多個檔案都配置了,默認使用第一次讀取到的,后續不覆寫
- 高優先級會覆寫低優先級
1.3 改變默認的組態檔位置
**專案打包好以后,我們可以使用命令列引數的形式,啟動專案的時候來指定組態檔的新位置;指定默認加載的這些組態檔共同起作用形成互補配置
**
在 G盤目錄下,創建一個application.properties檔案(yml也可以),定義埠為8085
打包專案,啟動命令列:
java -jar spring-boot-02-config-02.0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties
回車運行,
瀏覽器訪問: http:localhost:8005/boot02/hello ,顯然外部指定的組態檔生效了,并且與之前的主組態檔形成了互補配置
1.4 使用profile配置和加載組態檔
1.4.1 使用.properties
檔案
假如有開發、測驗、生產三個不同的環境,需要定義三個不同環境下的配置
application.properties
applicaiton-dev.properties
applictiong-test.properties
applicaiton-prod.properties
在application.properties
檔案中指定當前使用的環境:
server.port=8001
# 激活哪個組態檔
spring.profiles.active=dev
#spring.profiles.active=dev,prod,test
spring.profiles.include=prod
1.4.2 使用.yml
檔案
因為在yml檔案中,---
表示檔案分隔符,每個檔案獨立,所以此時只需要一個.yml
檔案
spring:
profiles:
active: prod
---
spring:
profiles: dev
server: 8080
---
spring:
profiles: test
server: 8081
---
spring.profiles: prod
spring.profiles.include:
- proddb
- prodmq
server: 8082
---
spring:
profiles: proddb
db:
name: mysql
---
spring:
profiles: prodmq
mq:
address: localhost
此時讀取的就是prod的配置,prod包含proddb,prodmq,此時可以讀取proddb,prodmq下的配置
也可以同時激活三個配置spring.profiles.active: prod,proddb,prodmq
1.4.3 使用Java中的@Profile
注解
@Profile
注解只能配合@Configuration
和@Component
使用
@Configuration
@Profile("prod")
public class ProductionConfiguration {
// ...
}
1.5 讀取自定義組態檔
1.5.1 利用 @PropertiesSource
注解來實作
@PropertiesSource 可以用來加載指定的組態檔,默認只能加載 *.properties
檔案, 不能加載 yml
等檔案
相關屬性
- value: 指明加載組態檔的路徑
- ignoreResourceNotFound:指定的組態檔不存在是否報錯,默認是false,當設定為 true 時,若該檔案不存在,程式不會報錯,實際專案開發中,最好設定
ignoreResourceNotFound 為 false, - encoding:指定讀取屬性檔案所使用的編碼,我們通常使用的是UTF-8,
示例
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Configuration
@PropertySource(value = https://www.cnblogs.com/zerozayu/archive/2023/07/10/{"classpath:common.properties"}, ignoreResourceNotFound = false, encoding = "UTF-8")
@ConfigurationProperties(prefix = "author")// 這個注解的作用是指明組態檔中需要注入資訊的前綴
public class Author {
private Stirng name;
private String job;
private String sex;
}
當需要用 yml
作為組態檔時此時我們可以通過實作PropertySourceFactory介面,重寫createPropertySource方法,就能實作用@PropertySource也能加載yaml等型別檔案,
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.util.StringUtils;
import java.io.FileNotFoundException;
import java.util.Properties;
public class YamlPropertiesSourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String sourceName, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYaml(resource);
if (StringUtils.isBlank(sourceName)) {
sourceName = resource.getResource().getFilename();
}
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYaml(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException) {
throw (FileNotFoundException) cause;
}
throw e;
}
}
}
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Configuration
// 指明上面寫好的工廠類
@PropertySource(factory = YamlPropertySourceFactory.class, value = https://www.cnblogs.com/zerozayu/archive/2023/07/10/{"classpath:user.yml"},
ignoreResourceNotFound = false, encoding = "UTF-8")
@ConfigurationProperties(prefix = "author")// 這個注解的作用是指明組態檔中需要注入資訊的前綴
public class Author {
private Stirng name;
private String job;
private String sex;
}
1.5.2 使用 EnvironmentPostProcessor
加載自定義組態檔
實作流程
- 實作EnvironmentPostProcessor介面,重寫postProcessEnvironment方法
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
String[] profiles = {"config/test.properties", "config/custom.properties", "config/blog.yml"};
for (String profile : profiles) {
Resource resource = new ClassPathResource(profile);
environment.getPropertySources().addLast(loadProfiles(resource));
}
}
private PropertySource<?> loadProfiles(Resource resource) {
if (!resource.exists()) {
throw new IllegalArgumentException("資源不存在");
}
if (resource.getFilename().endsWith("yml")) {
return loadYaml(resource);
} else {
return loadProperty(resource);
}
}
private PropertySource loadProperty(Resource resource) {
try {
Properties properties = new Properties();
properties.load(resource.getInputStream());
return new PropertiesPropertySource(resource.getFilename(), properties);
} catch (Exception e) {
throw new IllegalStateException("加載Property組態檔失敗", e);
}
}
private PropertySource loadYaml(Resource resource) {
try {
YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
factoryBean.setResources(resource);
Properties properties = factoryBean.getObject();
return new PropertiesPropertySource(resource.getFilename(), properties);
} catch (Exception e) {
throw new IllegalStateException("加載Yaml組態檔失敗", e);
}
}
}
- 在META-INF下創建spring.factories
# spring.factories 檔案內容如下:
# 啟用自定義環境處理類
org.springframework.boot.env.EnvironmentPostProcessor=com.zhangyu.config.MyEnvironmentPostProcessor
1.6 SpringBoot使用通配符加載組態檔
還可以使用通配符加載自定義組態檔,貌似是spring的實作方式
@Configuration
public class PropertyConfig {
@Bean
public PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() throws IOException {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setLocations(new PathMatchingResourcePatternResolver().getResources("classpath:properties/*.properties"));
return configurer;
}
}
classpath*:
和classpath:
的區別是
classpath:
: 只會到你的class路徑中查找找檔案,
classpath*:
: 不僅包含class路徑,還包括jar檔案中(class路徑)進行查找,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/556918.html
標籤:其他
上一篇:iota簡介
下一篇:返回列表