Home  >  Article  >  Backend Development  >  Detailed explanation of knowledge points of Spring Boot framework

Detailed explanation of knowledge points of Spring Boot framework

巴扎黑
巴扎黑Original
2017-08-16 09:37:324786browse


Summary: 1. Spring Boot’s property configuration file 1.1 The first form of Spring Boot’s property configuration file uses the properties configuration file, as follows: The meaning is to change the access port to 8081 and add a contextPath, which can be understood as adding an additional layer of address to the address bar. server.port= ...

1. Spring Boot property configuration file

1.1 The first form of Spring Boot’s property configuration file

Using the properties configuration file, the following two properties mean to change the access port to 8081, and added a contextPath, which can be understood as adding an additional layer of addresses to the address bar.

server.port=8081
server.context-path=/joyou

                                                                                                                                                                                                                together together. — — "Run As ——" Spring Boot App Startup Program

Detailed explanation of knowledge points of Spring Boot framework

# The effect is as follows. First, from the log, the port has changed to 8081

Detailed explanation of knowledge points of Spring Boot framework

The browser access effect is as follows.

                                                                                                                                                                                                                                                                                             ​The SpringApplication class provided by Spring Boot searches and loads the application.properties file to obtain configuration property values. The SpringApplication class will search for the file in the following location: Detailed explanation of knowledge points of Spring Boot framework

1.

/config subdirectory of the current directory

2.Current directory

3./config in classpath Package

4.classpath

The above sequence is also Indicates the priority of the properties files contained at this location. Priorities are arranged from high to low.

You can specify different property file names through the configuration attribute of the spring.config.name key. You can also add the search path for additional property files through spring.config.location.

##           

1.2 The second form of Spring Boot’s property configuration file (recommended)

Use yml to configure, and create the Application.yml file in the Resources directory. code show as below.

server:  port: 8082  context-path: /joyou

                效果与1.1相同。

                  补充:                   

                相对于属性文件来说,YAML 是一个更好的配置文件格式。当有前缀的情况下,使用.yml格式的配置文件更简单。

注意:使用.yml时,属性名的值和冒号中间必须有空格,如name: SpringBoot正确,SpringBoot就是错的。

YAML is used very well in Ruby on Rails. YAML is a superset of JSON and a convenient format for defining hierarchical configuration data. Its basic grammar rules are as follows:

  • Case sensitive

  • Use indentation Hierarchical relationship

  • The Tab key is not allowed when indenting, Only spaces are allowed.

  • The number of indented spaces is not important, as long as elements at the same level are left aligned

  • # represents a comment. From this character to the end of the line, it will be ignored by the parser.

1.3 Which keys in application.properties are configurable?

Detailed configuration and instructions are given in the SpringBoot official website documentation. In Appendix A. Common application properties: http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#common-application-properties

Incomplete statistics, this The complete application properties file has 1183 lines. Among them, there are 950 attribute keys. When you see such a huge configuration, you will definitely be shocked. However, in actual projects, if we follow Spring Boot's convention, we usually do not need to specify too many configurations separately.

1.4 About the configuration priority

## Spring Boot provides a mechanism for reading priority configuration to help us get out of this dilemma.

The configuration priority sequence provided by Spring Boot is relatively complex. In order of priority from high to low, the specific list (from high to low) is as follows.

  •                                         1. Command line parameters (highest priority).

  • 2. Java system parameters obtained through System.getProperties().

  • 3. Operating system environment variables.

  • 4. JNDI attributes obtained from java:comp/env.

  • 5. Random.* properties generated by RandomValuePropertySource.

  • This 6.jar Pack's Application- {Profile} .properties or Application.yml (with spring.profile) configuration files, via Spring.config.Location Parameter designation

  • ## 8. Application.properties or application.yml (without spring.profile) configuration file outside the jar package
  • 9. The application.properties or application.yml (without spring.profile) configuration file inside the jar package

  •                                                                                                                                                                                                    Use Java configuration classes, including Java classes annotated with @Configuration, and property files declared through @PropertySource annotations.

  • 11. Default properties declared through SpringApplication.setDefaultProperties.

If Spring Boot finds a configuration in a higher-priority location, it will ignore the lower-priority configuration. Below we briefly talk about these priorities. The configuration priority of Spring Boot seems complicated, but it is actually very reasonable. The priority of the command line parameters is set to the highest because it allows us to quickly modify the configuration parameter values ​​in a test or production environment without the need to repackage and deploy the application.

The SpringApplication class will by default convert the command line parameters starting with "--" into configurations that can be used in the application Parameter , such as "--name=Alex" will set the value of the configuration parameter "name" to "Alex".

If you don’t need this function, you can use SpringApplication.setAddCommandLineProperties(false)

Disable parsing of command line arguments.

2. Spring Boot custom properties

                2.1、 第一个自定义属性的例子  

                          在实际开发过程中,需要程序去配置文件中读取数据(如:URL,一些账号密码等),所以就需要我们来自定义属性,供程序读取。

                        首先在yml里自定一个属性,格式如下:

company: joyouemployee: 二十岁以后

                        在Java程序中取值,代码如下:

package com.example.demo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class HelloSpringBoot {	
	@Value("${company}")
	private String company;	
	@Value("${employee}")
	private String employee;	

	@RequestMapping(value="/hello" , method = RequestMethod.GET)
	public String HelloSpring(){		
			return company+"====="+employee;
	}
}

                使用浏览器访问效果如下

Detailed explanation of knowledge points of Spring Boot framework

#                                                             

## yml file configuration
company: joyouemployee: 二十岁以后   
All: "公司: ${company} , 员工: ${employee}"

                    在JAVA程序中注入All属性

package com.example.demo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class HelloSpringBoot {	
	@Value("${All}")	private String All;	
	
	@RequestMapping(value="/hello" , method = RequestMethod.GET)	public String HelloSpring(){		
			return All;
	}
}

            效果如图所示:

Detailed explanation of knowledge points of Spring Boot framework

            2.3 对于多个属性如何一次调用

                    看了上面的例子后,会产生一个疑问,如果想一次调用10个、20个、50个属性值,难道我要在程序中注入50次值,使用50次注解吗? 为了解决这个疑问,Spring Boot 是这么解决的!

                    首先一个女孩,有身高、体重、罩杯等等属性,我们可以这样来写!

Girl: 
   High: 160CM   Weight: 80KG   CupSize: 30A

                    然后写一个类,这个类中提供Girl的属性,及Setter,Geter方法,需要使用两个注解:

  •                     @Component //如果没有这个注解,会报找不到Bean的错

  •                     @ConfigurationProperties(prefix="Girl") //找到以Girl开头的属性

Detailed explanation of knowledge points of Spring Boot framework 

                    然后在java程序中注入Gril类

package com.example.demo;@RestControllerpublic class HelloSpringBoot {	@Autowired
	private Girl girl;	
	
	@RequestMapping(value="/hello" , method = RequestMethod.GET)
	public String HelloSpring(){		
			return girl.toString();
	}
}

                启动程序,刷新浏览器,效果如下:

Detailed explanation of knowledge points of Spring Boot framework

3. Multi-environment attribute configuration

##                                                                                                      

                                                                                                              Faced with different scenarios of production and development, the values ​​​​of some attributes may be different. Do I need to change the attribute values ​​written in the development environment one by one in the production environment? Now that I have said that, of course there is no need for it. We can write two sets of yml files with different requirements for attribute values ​​in the two environments during development, and then call the required yml files.

For the attribute value of the production environment GIRL:

Detailed explanation of knowledge points of Spring Boot framework

This is as follows:

Detailed explanation of knowledge points of Spring Boot framework

# I just need to call different files in application.yml. The value dev is the suffix name of different yml files in my development and production environments (Pay attention to the naming of the two image files above

)# ##

Detailed explanation of knowledge points of Spring Boot framework

The result corresponding to the browser

Detailed explanation of knowledge points of Spring Boot framework

## The configuration corresponding to the second environment

Detailed explanation of knowledge points of Spring Boot framework

The results corresponding to the browser

Detailed explanation of knowledge points of Spring Boot framework

Add a picture of the project directory structure so far to help understand

Detailed explanation of knowledge points of Spring Boot framework

The above is the detailed content of Detailed explanation of knowledge points of Spring Boot framework. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn