Springboot 讀取配置文件中的配置項賦值給靜態常量
在實際應用中,有這樣的使用場景,需要設置全局變量,一般方法是寫一個常量類,將全局變量保存爲常量類的靜態成員變量,這個方法的缺點是如果常量需要修改,或者在多環境(dev、test、prod)項目中,不同環境的常量也不同,此時,可以將該常量寫在配置文件裏。如此,就有了如題目的需求,將配置文件中的配置項初始化爲靜態常量。
背景介紹
1. 確定要加載的配置文件的方式
- 本文參考了各種加載配置文件的方式,爲了實現讓 springboot 自動根據啓動參數找到指定的配置文件,而不是採用硬編碼讀取指定路徑下指定名稱的配置文件,所以使用 @Value 註解的方式來加載配置項
2. 不同環境的切換方式
- 本文參考了各種環境的切換方式,爲了實現使用完全相同的一套代碼,來切換不同環境(而不是把配置文件信息寫在代碼中),本文中選擇在項目啓動時設置啓動參數 --spring.profiles.active=dev 的方法來確定要讀取的配置文件
- 本文沒有使用修改 pom.xml 的方式
3. 加載配置文件中配置項的方式
- 本文使用在常量類的構造器中加載配置項
4. 此處需要要了解下 sprintboot 的啓動順序 與 配置文件的加載順序
1. sprintboot 的啓動順序:從上至下
- 創建Bean
- 初始化Bean,給Bean的各成員變量賦值
2. 配置文件的加載順序:從上至下
- application.yml
- application.yaml
- application.properties
注意:本文只實現了常量類文件與 springboot 項目啓動類在同一module的情況,在多module項目中,如何實現跨module初始化常量類,尚需探索。
具體方法
1. 確定要讀取的配置文件
本文以一個 sprintboot 項目爲例,該項目的配置文件有4個:
- application.properties – 主配置文件
- application-dev.properties – dev環境的配置文件
- application-test.properties – test環境的配置文件
- application-prod.properties – prod環境的配置文件
2. 編寫常量類
要求 springboot 項目啓動時,自動加載配置項,並賦值給常量類中的靜態成員變量
-
- 在常量類的class聲明上加逐級 @Component
-
- 初始化靜態成員變量
-
- 創建構造方法(有參構造),在方法上加註解 @Autowired
-
- 在方法聲明的參數部分,使用 @Value 註解來獲取配置項的值,賦給類的靜態成員變量
項目啓動後會自動初始化該常量類並將配製文件中的各配置項賦值給類的靜態成員變量,供項目內各處調用
- 注意:本文只實現了常量類文件與 springboot 項目啓動類在同一module的情況,在多module項目中,如何實現跨module初始化常量類,尚需探索。
示例
代碼部分
- application.properties
# Tomcat
server.tomcat.max-threads=1000
server.tomcat.min-spare-threads=30
server.port=8080
# prod|test|dev 該配置項接收啓動命令參數
spring.profiles.active=${spring.profiles.active}
- application-dev.properties
# env flag
env.flag=dev
- application-test.properties
# env flag
env.flag=test
- application-prod.properties
# env flag
env.flag=prod
- 項目啓動類:DemoProjectApplication
@SpringBootApplication
public class AdRestApplication {
public static void main(String[] args) {
SpringApplication.run(AdRestApplication.class, args);
System.out.println("Current env :【 " + Constant.env + " 】 ");
}
}
- 常量類:Constant
@Component
public class Constant {
public static String env;
@Autowired
private Constant(@Value("${spring.profiles.active}") String env,
@Value("${ldap.url}") String ldapUrl) {
Constant.env = env;
}
}
執行結果
當啓動命令中 --spring.profiles.active=dev 爲例:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.4.RELEASE)
2020-03-15 16:45:38.075 [main] INFO com.xyy.ops.ad.rest.AdRestApplication - Starting AdRestApplication on arthas with PID 9272 (D:\Java_Project\ad-interface\ad-rest\target\classes started by c8 in D:\Java_Project\ad-interface)
2020-03-15 16:45:38.077 [main] INFO com.xyy.ops.ad.rest.AdRestApplication - The following profiles are active: dev
2020-03-15 16:45:39.082 [main] INFO o.s.boot.web.embedded.tomcat.TomcatWebServer - Tomcat initialized with port(s): 55070 (http)
2020-03-15 16:45:39.089 [main] INFO org.apache.coyote.http11.Http11NioProtocol - Initializing ProtocolHandler ["http-nio-55070"]
2020-03-15 16:45:39.090 [main] INFO org.apache.catalina.core.StandardService - Starting service [Tomcat]
2020-03-15 16:45:39.090 [main] INFO org.apache.catalina.core.StandardEngine - Starting Servlet engine: [Apache Tomcat/9.0.30]
2020-03-15 16:45:39.202 [main] INFO o.a.c.core.ContainerBase.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
2020-03-15 16:45:39.202 [main] INFO org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 1067 ms
2020-03-15 16:45:39.673 [main] INFO o.s.scheduling.concurrent.ThreadPoolTaskExecutor - Initializing ExecutorService 'applicationTaskExecutor'
2020-03-15 16:45:39.728 [main] INFO o.s.b.a.web.servlet.WelcomePageHandlerMapping - Adding welcome page: class path resource [static/index.html]
2020-03-15 16:45:39.837 [main] INFO o.s.ldap.core.support.AbstractContextSource - Property 'userDn' not set - anonymous context will be used for read-write operations
2020-03-15 16:45:39.889 [main] INFO org.apache.coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-55070"]
2020-03-15 16:45:39.911 [main] INFO o.s.boot.web.embedded.tomcat.TomcatWebServer - Tomcat started on port(s): 55070 (http) with context path ''
2020-03-15 16:45:39.914 [main] INFO com.xyy.ops.ad.rest.AdRestApplication - Started AdRestApplication in 2.24 seconds (JVM running for 3.03)
Current env :【 dev 】