SpringBoot
It is a product born to simplify a series of problems such asSpring
application creation, operation, debugging, and deployment.自动装配的特性让我们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖就可以轻易的搭建出一个 WEB 工程
The previous article introduced the
SpringBoot
origin and construction method. Through the tutorial in the first chapter, weSpringBoot
are unfamiliar with the absence. We can find thatSpringBoot
although the XML has been eliminated, it has not achieved zero configuration . It reflects a kind of convention over configuration, also known as press Programming by convention, a software design paradigm, aims to reduce the number of decisions a software developer has to make and gain the benefits of simplicity without losing flexibility. In general, the default configuration is enough to meet the needs of daily development, but in special cases, we often need to use a series of functions such as custom property configuration, custom file configuration, multi-environment configuration, and external command guidance . Don't worry, theseSpringBoot
are all considered for us, we just need to follow its rules to configurepremise
In order to generate data
SpringBoot
better , we need to add the following dependencies ( this dependency can be omitted, but there will be no attribute prompts in IDEA and STS, and the configuration without prompts is as hard as writing code with Notepad, so let's take a look The problem will make you cry ), the dependency will only be called at compile time, so don't worry about affecting production...<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
Custom property configuration
application.properties
Write the following configuration content inmy1.age=22 my1.name=battcn
Secondly, define the
MyProperties1.java
file to map ourapplication.properties
content in , so that we can get the content of the configuration file by manipulating the objectpackage com.battcn.properties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * @author Levin * @since 2018/4/23 0023 */ @Component @ConfigurationProperties(prefix = "my1") public class MyProperties1 { private int age; private String name; // 省略 get set @Override public String toString() { return "MyProperties1{" + "age=" + age + ", name='" + name + '\'' + '}'; } }The next step is to define our code
PropertiesController
for injectingMyProperties1
and testing the code we wrote. It is worth noting that in theSpring4.x
future , it is recommended to inject properties in the form of constructors...import com.battcn.properties.MyProperties1; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author Levin * @since 2018/4/23 0023 */ @RequestMapping("/properties") @RestController public class PropertiesController { private static final Logger log = LoggerFactory.getLogger(PropertiesController.class); private final MyProperties1 myProperties1; @Autowired public PropertiesController(MyProperties1 myProperties1) { this.myProperties1 = myProperties1; } @GetMapping("/1") public MyProperties1 myProperties1() { log.info("================================================================================================="); log.info(myProperties1.toString()); log.info("================================================================================================="); return myProperties1; } }Open the browser, enter the following address: http://localhost:8080/properties/1 , observe the console, if the following content is monitored, the program is correct
2018-04-23 15:51:43.145 INFO 15352 --- [nio-8080-exec-2] c.b.controller.PropertiesController : ================================================================================================= 2018-04-23 15:51:43.145 INFO 15352 --- [nio-8080-exec-2] c.b.controller.PropertiesController : MyProperties1{age=22, name='battcn'} 2018-04-23 15:51:43.145 INFO 15352 --- [nio-8080-exec-2] c.b.controller.PropertiesController : =================================================================================================
custom file configuration
Define
my2.properties
a , the naming of custom configuration files is not mandatory toapplication
start withmy2.age=22 my2.name=Levin my2.email[email protected]Second, define the
MyProperties2.java
file , which is used to map ourmy2.properties
content in .package com.battcn.properties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; /** * @author Levin * @since 2018/4/23 0023 */ @Component @PropertySource("classpath:my2.properties") @ConfigurationProperties(prefix = "my2") public class MyProperties2 { private int age; private String name; private String email; // 省略 get set @Override public String toString() { return "MyProperties2{" + "age=" + age + ", name='" + name + '\'' + ", email='" + email + '\'' + '}'; } }Next, use it
PropertiesController
to injectMyProperties2
and test the code we wrote@GetMapping("/2") public MyProperties2 myProperties2() { log.info("================================================================================================="); log.info(myProperties2.toString()); log.info("================================================================================================="); return myProperties2; }Open the browser, enter the following address: http://localhost:8080/properties/2 , observe the console, if the following content is monitored, the program is correct
2018-04-23 15:59:45.395 INFO 6232 --- [nio-8080-exec-4] c.b.controller.PropertiesController : ================================================================================================= 2018-04-23 15:59:45.395 INFO 6232 --- [nio-8080-exec-4] c.b.controller.PropertiesController : MyProperties2{age=22, name='Levin', email='[email protected]'} 2018-04-23 15:59:45.395 INFO 6232 --- [nio-8080-exec-4] c.b.controller.PropertiesController : =================================================================================================Multi-environment configuration
In real applications, there are often multiple environments ( such as development, testing, production, etc. ), and the database connections in different environments are different. At this time, you need to use
spring.profile.active
the powerful functions of . Its format isapplication-{profile}.properties
, here Theapplication
prefix cannot be changed, it{profile}
is defined by ourselves.Create
application-dev.properties
,application-test.properties
,application-prod.properties
, the contents are as followsapplication-dev.properties
server.servlet.context-path=/devapplication-test.properties
server.servlet.context-path=/testapplication-prod.properties
server.servlet.context-path=/prodWrite in the
application.properties
configuration file.spring.profiles.active=dev
At this time , it is useless to visit http://localhost:8080/properties/1context-path=/dev
, because we set it , so the new path is http://localhost:8080/dev /properties/1 , it can be seen that the property values read by different configurations are different.external command boot
The first three methods are all based on the configuration file level, so is there any way to guide it externally? Assuming such a scenario, we package and release the code that has been developed. During the period, the test in the test environment passes the test, then it can be released for production. At this time, it is convenient to modify
application.properties
the configuration or configure it directly in the command parameters . There is no doubt that the latter is more convincing. By default,SpringApplication
command-line option arguments (ie: --property, such as --server.port=9000) are added to the Environment, and command-line properties always take precedence over other property sources.
How to test?
- Go to the project directory, here is my local directory: F:/battcn-workspace/spring-boot2-learning/chapter2
- Then open the cmd program, if you will not open cmd in the current directory, please Baidu by yourself, enter:
mvn package
- After packaging, go to: F:/battcn-workspace/spring-boot2-learning/chapter2/target directory, we can find a package named chapter2-0.0.1-SNAPSHOT.jar
- Then open the cmd program and enter:
java -jar chapter2-0.0.1-SNAPSHOT.jar --spring.profiles.active=test --my1.age=32
. Carefully observe whether the key valuesspring.profiles.active=test
ofmy1.age=32
these two configurations are familiar (if you don't know it, please read it carefully from the beginning)- Finally enter the test address: http://localhost:8080/test/properties/1 We can find
{"age":32,"name":"battcn"}
that correctSummarize
- Master
@ConfigurationProperties
the@PropertySource
usage and function of annotations- Mastering Writing Custom Configurations
- Master the way external commands guide configuration
At present, many big guys have
SpringBoot
written tutorials about . If there are any similarities, please bear with me. This tutorial is based on the latest .spring-boot-starter-parent:2.0.1.RELEASE
The features of the new version will be introduced together…