In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Today, I will talk to you about the file configuration of application.yml in springboot, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
Springboot profile
Springboot is the easiest place, one is out of the box, the other is simple configuration, the configuration file path is generally under / src/main/resources, the main configuration has two forms, one is the properties file, the other is the yml suffix file officially recommended by springboot
1. Configure spring in properties/yml file
Use the properties file springboot configuration
# configure the built-in tomcat startup port server.port=8080# to name the program spring.application.name=boot-helloworld
Properties file, as the leader of many configuration files, is easy to use and has a simple format. The left side of the equal sign is the attribute and the right side is the value, which can be said to be simple and convenient.
Use the yml file as the springboot configuration
# configure the built-in tomcat startup port server: port: 808 boot application name spring: application: name: boot-helloworld
In the yml file, there is a strict hierarchical relationship, expressed by spaces or Tab indentation, ending with a colon, leaving at least one English space at the end of the level, and then filling in the value of the attribute. The advantage is that the hierarchical representation can simply write multiple values together, for example:
Spring: application: name: boot-helloworld#redis connection pool configuration, can wrap lines to keep indentation, and write redis: host: localhost port: 6379 password: password timeOut: 5000 maxIdle: 50 maxWaitMillis: 5000 maxTotal: 500II, springboot common configuration items
The following is an excerpt from spring-configuration-metadata.json in spring-boot-autoconfiguration.jar. In addition, the default configuration of springboot is specified in the spring-autoconfigure-metadata.properties file in this package. Students who need it can look it up. Different springboot versions have different default attributes.
Specify project startup port
Server: port: 8081
Assign a name to the project
Spring: application: name: boot-helloworld
Log level
# by default, springboot uses Logback as the logging framework # logging.level to start with, specify a dependent groupId, and then specify the log level logging: level: org.springframeword.web: debug
Specify the configuration environment for startup in multiple environments
# you only need to set spring.profiles.active=prod in application.properties to specify the active profile # the following indicates that application-test.yml# is used and default (application.yml) is used by default, so that you can distinguish between development, online, test, preview and other environments spring: profiles: active: test
Specify the project path
# add / bootserver: servlet: context-path: / boot before all interface access paths. 3. Read custom attributes based on @ Value annotation
The following code is for demonstration purposes only
1: User.java
/ * as a configuration item, simply deal with * @ author Calvin * @ date 2019-07-24 * / public class User {/ * * ID * / private String id; / * * name * / private String userName; / * age * / private Integer age; / * gender * / private String gender / * operating system used * / private String systemName; public String getId () {return id;} public void setId (String id) {this.id = id;} public String getUserName () {return userName;} public void setUserName (String userName) {this.userName = userName;} public Integer getAge () {return age } public void setAge (Integer age) {this.age = age;} public String getGender () {return gender;} public void setGender (String gender) {this.gender = gender;} public String getSystemName () {return systemName;} public void setSystemName (String systemName) {this.systemName = systemName } @ Override public String toString () {return "User {" + "id='" + id +'\'+ ", userName='" + userName +'\'+ ", age=" + age + ", gender='" + gender +'\'+ " SystemName=' "+ systemName +'\'+'}' }}
2: application.yml
Spring: application: name: boot-helloworldlogging: level: org.springframeword.web: debugserver: servlet: context-path: / boot# admin Age configuration admin: age: 20
3:ValueController.java
/ * * various ways to test @ Value annotations * @ author Calvin * @ date 2019-07-24 * / @ RestController@RequestMapping ("/ value") public class ValueController {/ * ID uses expression annotations * / @ Value ("# {T (java.util.UUID). RandomUUID ()}") private String adminId / * name uses value annotations to get a UUID * / @ Value ("Calvin") private String adminName; / * gender given a default value, if not defined, use the default value * / @ Value ("${admin.gender: male}") private String adminGender / * inject admin.age * / @ Value ("${admin.age}") private Integer adminAge; / * into the yml file to obtain the system variable * / @ Value ("# {systemProperties ['os.name']}") private String systemName by expression / * get user information * @ return * / @ GetMapping ("/ getUserInfo") public User getAdminInfo () {User admin = new User (); admin.setId (adminId); admin.setUserName (adminName); admin.setAge (adminAge); admin.setGender (adminGender); admin.setSystemName (systemName); return admin;}}
4: call result
Springboot configuration files can not only use @ Value annotations, there are many fun ways, another can use @ ConfigurationProperties to inject into a Bean, the specific method is not investigated here
IV. Interpretation of yml configuration file loading source code
It is not easy to interpret the source code. The author wrote this part only after referring to a lot of resources on the Internet. I hope you can give me a lot of advice. I won't draw any pictures here, and my drawing skills are not good.
1: call chain
BootApplication.main ()
/ / main method, program entry SpringApplication.run (BootApplication.class, args)
SpringApplication.run (): 1202
/ / instantiate SpringApplication and call the run method return new SpringApplication (primarySources) .run (args)
SpringApplication.run (): 304
/ / instantiate EnvironmentConfigurableEnvironment environment = prepareEnvironment (listeners, applicationArguments) in this method
SpringApplication.prepareEnvironment (): 338
/ / because I am a Web program and use spring-boot-starter-web dependencies, it is StandardServletEnvironmentprivate ConfigurableEnvironment getOrCreateEnvironment () {/ / omitting part of the code return new StandardServletEnvironment ();} / / because of StandardServletEnviroment extends AbstractEnvironment//, the customizePropertySources () method public AbstractEnvironment () {/ / template method is called in the AbstractEnvironment constructor, and everyone knows customizePropertySources (this.propertySources);}
StandardServletEnvironment.customizePropertySources (): 54
Protected void customizePropertySources (MutablePropertySources propertySources) {/ / add servletConfigInitParams to PropertySource propertySources.addLast (new StubPropertySource (SERVLET_CONFIG_PROPERTY_SOURCE_NAME)); / / add servletContextInitParams to PropertySource propertySources.addLast (new StubPropertySource (SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)); if (JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable ()) {propertySources.addLast (new JndiPropertySource (JNDI_PROPERTY_SOURCE_NAME)) } / / call the AbstractEnvironment.customizePropertySources () method super.customizePropertySources (propertySources);}
AbstractEnvironment.customizePropertySources (): 77
@ Overrideprotected void customizePropertySources (MutablePropertySources propertySources) {/ / add systemProperties, add System.getProperties (), is a Native method, and the main attribute is / / java.runtime.name | propertySources.addLast (new PropertiesPropertySource (SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties ()) of system configuration such as java.vm.version) / / add systemEnvironment, that is, the system environment variable, which contains attributes such as JAVA_HOME propertySources.addLast (new SystemEnvironmentPropertySource (SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment ();}
At this point, four propertySource have been added to the ConfigurableEnvironment object, namely:
[servletConfigInitParams, servletContextInitParams, systemProperties, systemEnvironment]
After reading what SpringApplication.prepareEnvironment (): 338 has done, then look at listeners.environmentPrepared (environment): 340, which is also the entry for yml file configuration
SpringApplicationRunListeners.environmentPremared
Public void environmentPrepared (ConfigurableEnvironment environment) {for (SpringApplicationRunListener listener: this.listeners) {listener.environmentPrepared (environment);}}
Many Listener are loaded in this method, and each call chain is very deep, so let's make it short.
SpringApplicationRunListeners.java
EnvironmentPrepared-- >
SimpleApplcationEventMulticaster.java
MulticastEvent (): 126mm 131muri->
InvokeListener (): 159Mui->
DoInvokeListener (listener, event)-- >
CofigFileApplicationListener.java
OnApplicationEvent ():->
AddPostProcessors ();-- >
New Loader (environment, resourceLoader). Load (): 202->
Load (String location, String name, Profile profile, DocumentFilterFactory filterFactory,DocumentConsumer consumer): 429muri->
The front high energy, the author follows the code very hard, nonsense, the core code in ConfigFileApplicationListener.java
ConfigFileApplicationListener.onApplicationEvent ()
@ Overridepublic void onApplicationEvent (ApplicationEvent event) {if (event instanceof ApplicationEnvironmentPreparedEvent) {onApplicationEnvironmentPreparedEvent ((ApplicationEnvironmentPreparedEvent) event);} if (event instanceof ApplicationPreparedEvent) {onApplicationPreparedEvent (event);}}
ConfigFileApplicationListener.load ()
Private void load (String location, String name, Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer) {if (! StringUtils.hasText (name)) {for (PropertySourceLoader loader: this.propertySourceLoaders) {if (canLoadFileExtension (loader, location)) {load (loader, location, profile, filterFactory.getDocumentFilter (profile), consumer) Return;} Set processed = new HashSet () / / traverse propertySourceLoaders for (PropertySourceLoader loader: this.propertySourceLoaders) {for (String fileExtension: loader.getFileExtensions ()) {if (processed.add (fileExtension)) {/ / find the configuration file loadForFileExtension (loader, location + name, "." + fileExtension, profile, filterFactory) Consumer) }}
There are two classes in this.propertySourceLoaders, both of which are implementation classes of PropertySourceLoader, respectively
[org.springframework.boot.env.PropertiesPropertySourceLoader, org.springframework.boot.env.YamlPropertySourceLoader]
PropertiesPropertySourceLoader.java
/ *
* this type of configuration file responsible for loading the ["properties", "xml"] suffix * loadProerties is responsible for reading the contents of the configuration file *
* / public class PropertiesPropertySourceLoader implements PropertySourceLoader {private static final String XML_FILE_EXTENSION = ".xml"; @ Override public String [] getFileExtensions () {return new String [] {"properties", "xml"};} @ Override public List properties = loadProperties (resource); if (properties.isEmpty ()) {return Collections.emptyList () } return Collections.singletonList (new OriginTrackedMapPropertySource (name, properties));} @ SuppressWarnings ({"unchecked", "rawtypes"}) private Map loadProperties (Resource resource) throws IOException {String filename = resource.getFilename () If (filename! = null & & filename.endsWith (XML_FILE_EXTENSION)) {return (Map) PropertiesLoaderUtils.loadProperties (resource);} return new OriginTrackedPropertiesLoader (resource). Load ();}}
YamlPropertySourceLoader.java
/ *
* this type of configuration file responsible for loading the ["yml", "yaml"] suffix * load is responsible for reading the contents of the configuration file *
* / public class YamlPropertySourceLoader implements PropertySourceLoader {@ Override public String [] getFileExtensions () {return new String [] {"yml", "yaml"};} @ Override public List > propertySources = new ArrayList (loaded.size ()); for (int I = 0; I
< loaded.size(); i++) { String documentNumber = (loaded.size() != 1) ? " (document #" + i + ")" : ""; propertySources.add(new OriginTrackedMapPropertySource(name + documentNumber, loaded.get(i))); } return propertySources; }} 至此结束,找到了加载application.yml文件的位置,接着往下跟 会在此方法中加载,具体调用了Yaml类构造器,StreamReader去读取文件 public List load() { final List result = new ArrayList(); process((properties, map) ->Result.add (getFlattenedMap (map)); return result;}
YamlProcessor.java
Private void buildFlattenedMap (Map result, Map source, @ Nullable String path) {source.forEach ((key, value)-> {if (StringUtils.hasText (path)) {if (key.startsWith ("[")) {key = path + key } else {key = path +'.'+ key;}} if (value instanceof String) {result.put (key, value) } else if (value instanceof Map) {/ / Need a compound key @ SuppressWarnings ("unchecked") Map map = (Map) value; buildFlattenedMap (result, map, key) } else if (value instanceof Collection) {/ / Need a compound key @ SuppressWarnings ("unchecked") Collection collection = (Collection) value; if (collection.isEmpty ()) {result.put (key, ") } else {int count = 0 For (Object object: collection) {buildFlattenedMap (result, Collections.singletonMap ("[" + (count++) + "]", object), key) } else {result.put (key, (value! = null? Value: "));}});}
A little nonsense, this loaded call chain is very deep, six or seven classes, no less than a dozen methods, interested students can study, students learning to use please do not pay too much attention to this, but reading the source code helps to better understand the framework, if there are different understandings or errors in the text, welcome to correct.
5. Summary
1: briefly explain the two configuration files commonly used in springboot
2: based on the two configuration files, do the implementation respectively
Common ways to annotate 3:@Value
Interpretation of 4:yml File loading Source Code
After reading the above, do you have any further understanding of the file configuration of application.yml in springboot? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
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.