[Practice] has Springboot reads the configuration items in the configuration file is assigned to static constants

Configuration Item Springboot reads the configuration file is assigned to static constants

In practical applications, such usage scenarios, you need to set a global variable, the general approach is to write a constant class, save the global variables as static member variables constant class disadvantage of this method is that if the constant need to change, or in multi-environment (dev, test, prod) project, constants different environments are different, this time, you can write the constants in the configuration file. So, there is a demand for such topics,The configuration items in the configuration file to initialize a static constant


Background

1. Determine ways to load configuration file

  • This reference to various load profiles, and in order to achieve let springboot automatically find the specified configuration file according to the startup parameters, rather than using the configuration file specifies the name of the hard-coded read the specified path, soUse @Value annotation way to load configuration items

2. The switching method different environments

  • This reference to a variety of environments switching manner, in order to achieve the exact same set of code used to switch to a different environment (rather than write the profile information in the code), selected hereinSet the startup parameter when a project starts The method of --spring.profiles.active = devTo determine the configuration file to be read
  • This article is not used to modify the way pom.xml

3. Load the configuration file in the way of configuration items

  • As used herein, load the configuration items in the constants class constructor

4. Here you need to understand the order of the boot sequence to load the configuration file under the sprintboot

1. sprintboot the boot sequence: from top to bottom

  1. Creating Bean
  2. Initialization Bean, Bean to each member variable assignment

2. configuration file load order: top to bottom

  1. application.yml
  2. application.yaml
  3. application.properties

note: This article only achieve a constant class file and springboot project start classes in the case of the same module, multi-module project, how to achieve inter-module initialization constants class, still need to explore.

specific method

1. Determine the configuration file to be read

In this paper, a sprintboot project as an example, the project's configuration file has four:

  • application.properties - the main configuration file
  • application-dev.properties - dev environment profile
  • application-test.properties - test environment profile
  • application-prod.properties - prod environment profile

2. Write constants class

When required springboot project start, automatic load the configuration items, and assigned to the static member variables constant class

    1. @Component added step by step in the class declaration of class constants
    1. Initialize static member variables
    1. Create a constructor (there is argument constructor), plus comment on the method @Autowired
    1. In the declaration part of the method parameters, use @Value notes to get the value of configuration items, static member variables assigned to the class

Automatically initialize static member variables assigned to each configuration item classes and the constant class configuration file in the project started, around calls for projects within

  • Note: This article only achieve a constant class file and springboot project start classes in the case of the same module, multi-module project, how to achieve inter-module initialization constants class, still need to explore.

Examples

Code section

  • 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
  • Project startup class: DemoProjectApplication
@SpringBootApplication
public class AdRestApplication {
    public static void main(String[] args) {
        SpringApplication.run(AdRestApplication.class, args);
        System.out.println("Current env :【 " + Constant.env + " 】 ");
    }
}
  • Class constants: 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;
    }
}

Results of the

When the start command --spring.profiles.active = dev example:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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 】 
Published 57 original articles · won praise 35 · Views 100,000 +

Guess you like

Origin blog.csdn.net/achuDk/article/details/104892107