In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you how springboot reads configuration files to static utility classes. I hope you will get something after reading this article. Let's discuss it together.
Springboot reads the configuration file to the static utility class
Usually we can read the configuration file with @ Value annotations and @ Configuration,@ConfigurationProperties (prefix = "xxx") annotations, but it is impossible to read the configuration to static variables, and we cannot use these two methods if we want to load the configuration file into a utility class during project initialization and then call it through static variables.
We can solve it with Environment.
Cut the crap and go straight to the code.
Import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.env.Environment;import org.springframework.stereotype.Component; / * @ Description: configure constant classes-load different configurations according to different spring-profile * @ author: eric.zhang * @ date: 10:59:24 * / @ Componentpublic class ConfigConstant {@ Autowired private Environment env; public static String url; public static String param on July 20, 2018 @ PostConstruct public void readConfig () {url = env.getProperty ("config.url"); param = env.getProperty ("config.param");}}
After I finished writing, I found some trouble. Here are the improved methods. Instead of get every configuration, you just need to write the key of the configuration file the same as the static variable name of the tool class.
Import java.io.UnsupportedEncodingException;import java.lang.reflect.Field; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.env.Environment;import org.springframework.stereotype.Component / * @ Description: configure constant class-load different configurations according to different spring-profile, and the variable name should be the same as the name written in the configuration file * @ author: eric.zhang * @ date: 10:59:24 * / @ Componentpublic class ConfigConstant {@ Autowired private Environment env; public static String url; public static String name; @ PostConstruct public void readConfig () throws Exception {String prefix = "config." Field [] fields = ConfigConstant.class.getFields (); for (Field field: fields) {field.set (null, getProperty (prefix + field.getName ());}} private String getProperty (String key) throws UnsupportedEncodingException {return new String (env.getProperty (key) .getBytes ("ISO-8859-1"), "UTF-8");}}
The eldest brother said that it is inconvenient to write spring-dependent code, so he wrote a version that does not rely on spring.
Import java.io.InputStreamReader;import java.lang.reflect.Field;import java.util.Properties; / * @ Description: configure constant class-load different configuration * variable names according to different spring-profile to change the "." in the key of the configuration file. Replace with "_" name * @ author: eric.zhang * @ date: 10:59:24 * / public class ConfigConstant {public static String CONFIG_URL; public static String CONFIG_NAME; static {try {Properties props = new Properties (); props.load (new InputStreamReader (ConfigConstant.class.getClassLoader (). GetResourceAsStream ("application.properties"), "UTF-8")) String profile = props.getProperty ("spring.profiles.active"); String envFile = "application-" + profile + ".properties"; Properties envProps = new Properties (); envProps.load (new InputStreamReader (ConfigConstant.class.getClassLoader (). GetResourceAsStream (envFile), "UTF-8")); Field [] fields = ConfigConstant.class.getFields () For (Field field: fields) {field.set (null, envProps.getProperty (field.getName (). Replace ("_", ".). ToLowerCase ());}} catch (Exception e) {e.printStackTrace ();} load the value of the configuration file into the static variable of the utility class (multi-environment running load) first create a SpringBoot project
Project structure:
Create a pom file that maps the maven project dependencies
4.0.0 com.csrcb spring_static 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.1.6.RELEASE org.springframework.boot spring-boot-starter-web org.projectlombok lombok create profile
Under the resource directory, create a configuration file application.yml, create several configuration files for application-dev,application-sit and application-prod.yml in different environments, and test them later to see whether to load the values of configuration parameters in different environments.
Application.yml is simply the configuration of a port number:
Set some values in application-dev.yml (values of configuration parameters for development environment), sit (testing), uat (verification), and prod (production) environments
The values of the configuration parameters of the tests in different environments are different. In order to test whether the values of the corresponding running environment are obtained under the same parameter name setting,
Create an entity class
1. Create a configuration class that loads the configuration file
/ * @ Classname TestConfig * @ Description loads the configuration class of the configuration file * @ Date 16:28 on 2020-6-16 * @ Created by gangye * / @ Configuration@Datapublic class TestConfig {@ Value ("${ftp.username}") private String username; @ Value ("${ftp.passwd}") private String passwd; @ PostConstruct public void init () {ClientUtil.setConfigInfo (this);}}
two。 Create a tool class, which gets the parameter values of the configuration class
/ * * @ Classname ClientUtil * @ Description utility class, which introduces configuration file data into static variables through config * @ Date 16:29 on 2020-6-16 * @ Created by gangye * / @ Slf4jpublic class ClientUtil {private static String USERNAME; private static String PASSWD; public static void setConfigInfo (TestConfig testConfig) {ClientUtil.USERNAME = testConfig.getUsername (); ClientUtil.PASSWD = testConfig.getPasswd () } public static String getValue () {log.info ("get the value of the username of the profile: {}", USERNAME); return USERNAME;}}
3. Create a route to simulate a call
/ * @ Classname controller * @ Date, 2020-6-16 16:35 * @ Created by gangye * / @ RestController@RequestMapping (value = "/ test") public class TestController {@ GetMapping ("/ getvalue") public String getValue () {return ClientUtil.getValue ();}}
4. Create a startup class and add Bean to the startup class. In order to prevent the @ Value annotation of the configuration class at startup from finding the value in the configuration file, a configuration file cannot find it.
/ * * @ Classname AppStart * @ Description launch class * @ Date 16:26 on 2020-6-16 * @ Created by gangye * / @ SpringBootApplicationpublic class AppStart {public static void main (String [] args) {SpringApplication.run (AppStart.class,args);}}
Add the corresponding runtime environment settings at startup
-Dspring.profiles.active=sit
If the springboot version is lower, it may appear
Java.lang.IllegalArgumentException: errors like Could not resolve placeholder 'username' in value "${ftp.username}"
Solution: add the following code to the startup class
/ * Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'name' in value "${name}" * @ Description to prevent the @ Value annotation of the configuration class at startup from finding the value in the configuration file, a configuration file cannot be found. * @ Date 14:40:08, June 17, 2020 * @ return * / @ Bean public static PropertySourcesPlaceholderConfigurer placeholderConfigurer () {PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer () C.setIgnoreUnresolvablePlaceholders (true); return c;}
Start the environment again (under sit)
Enter: http://localhost:8000/test/getvalue in the browser
Then specify the operation under the prod environment
Use the browser to request routing
After reading this article, I believe you have a certain understanding of "how to read springboot configuration files to static tools". If you want to know more about it, welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.