【已实践】Springboot 读取配置文件中的配置项赋值给静态常量

Springboot 读取配置文件中的配置项赋值给静态常量

在实际应用中,有这样的使用场景,需要设置全局变量,一般方法是写一个常量类,将全局变量保存为常量类的静态成员变量,这个方法的缺点是如果常量需要修改,或者在多环境(dev、test、prod)项目中,不同环境的常量也不同,此时,可以将该常量写在配置文件里。如此,就有了如题目的需求,将配置文件中的配置项初始化为静态常量


背景介绍

1. 确定要加载的配置文件的方式

  • 本文参考了各种加载配置文件的方式,为了实现让 springboot 自动根据启动参数找到指定的配置文件,而不是采用硬编码读取指定路径下指定名称的配置文件,所以使用 @Value 注解的方式来加载配置项

2. 不同环境的切换方式

  • 本文参考了各种环境的切换方式,为了实现使用完全相同的一套代码,来切换不同环境(而不是把配置文件信息写在代码中),本文中选择在项目启动时设置启动参数 --spring.profiles.active=dev 的方法来确定要读取的配置文件
  • 本文没有使用修改 pom.xml 的方式

3. 加载配置文件中配置项的方式

  • 本文使用在常量类的构造器中加载配置项

4. 此处需要要了解下 sprintboot 的启动顺序 与 配置文件的加载顺序

1. sprintboot 的启动顺序:从上至下

  1. 创建Bean
  2. 初始化Bean,给Bean的各成员变量赋值

2. 配置文件的加载顺序:从上至下

  1. application.yml
  2. application.yaml
  3. 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 项目启动时,自动加载配置项,并赋值给常量类中的静态成员变量

    1. 在常量类的class声明上加逐级 @Component
    1. 初始化静态成员变量
    1. 创建构造方法(有参构造),在方法上加注解 @Autowired
    1. 在方法声明的参数部分,使用 @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 】 
发布了57 篇原创文章 · 获赞 35 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/achuDk/article/details/104892107