In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to understand the configuration file application.properties in springboot". In the daily operation, I believe many people have doubts about how to understand the configuration file application.properties in springboot. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to understand the configuration file application.properties in springboot". Next, please follow the editor to study!
Preface
Spring Boot uses the concept of "habit over configuration" (there are a lot of configurations in the project, and a habitual configuration is built in so that you don't have to configure it manually) to get your project up and running fast. Therefore, if we want to play Spring Boot, we need to know how to turn on the default configuration of each function module, which requires understanding the Spring Boot configuration file application.properties.
Text
Spring Boot uses a global configuration file, application.properties, in the src/main/resources directory or / config in the classpath. The global configuration file of Sping Boot is used to modify the configuration values of some default configurations.
Next, let's unveil the configuration file.
Note: if your project does not have this application.properties, create a new one in the src/main/java/resources directory.
Custom attribute
Application.properties provides support for custom properties, so we can configure some constants here:
Com.dudu.name= "du du MD" com.dudu.want= "wish you all good luck in the year of the Rooster."
Then you can bind to the attribute you want by annotating @ Value (value= "${config.name}") directly where you want to use it.
@ RestControllerpublic class UserController {@ Value ("${com.dudu.name}") private String name; @ Value ("${com.dudu.want}") private String want; @ RequestMapping ("/") public String hexo () {return name+ "," + want;}} "
We start the project and enter http://localhost:8080 to see the print "Doodle MD wish you all good luck in the year of the Rooster".
Sometimes there are too many attributes and it is too tiring to bind to attribute fields one by one. Officials advocate binding an object's bean. Here we build a ConfigBean.java class. At the top, you need to use the annotation @ ConfigurationProperties (prefix = "com.dudu") to indicate which one to use.
@ ConfigurationProperties (prefix = "com.dudu") public class ConfigBean {private String name; private String want; / / omit getter and setter}
After configuration here, you also need to add @ EnableConfigurationProperties to the spring Boot entry class and indicate which bean to load. If you do not write ConfigBean.class, add it to the bean class.
@ SpringBootApplication@EnableConfigurationProperties ({ConfigBean.class}) public class Chapter2Application {public static void main (String [] args) {SpringApplication.run (Chapter2Application.class, args);}}
Finally, you can introduce ConfigBean into Controller, as follows:
@ RestControllerpublic class UserController {@ Autowired ConfigBean configBean; @ RequestMapping ("/") public String hexo () {return configBean.getName () + configBean.getWant ();}} references between parameters
It can also be used by direct references between parameters in application.properties, like the following settings:
Com.dudu.name= "du du MD" com.dudu.want= "wish you all good luck in the year of the Rooster" com.dudu.yearhope=$ {com.dudu.name} here ${com.dudu.want}
So we can just use the yearhope attribute.
Use Custom Profil
Sometimes we don't want to put all the configurations in application.properties, so we can define another one. Here I explicitly name it test.properties, and the path is also placed under src/main/resources.
Com.md.name= "yo Xi ~" com.md.want= "wish you all good luck in the year of the Rooster."
Let's create a new bean class, as follows:
@ Configuration@ConfigurationProperties (prefix = "com.md") @ PropertySource ("classpath:test.properties") public class ConfigTestBean {private String name; private String want; / / omit getter and setter}
Note here, oh, there is a problem. If you are using a version prior to 1.5, you can specify the location of the properties file through locations, so:
@ ConfigurationProperties (prefix = "com.md", locations= "classpath:test.properties")
However, this attribute has not been available since version 1.5. It took a long time to find that @ Configuration and @ PropertySource ("classpath:test.properties") were added before you could read it.
Random value configuration
${random} in the configuration file can be used to generate different types of random values, thus simplifying the hassle of code generation, such as generating int values, long values, or string strings.
Dudu.secret=$ {random.value} dudu.number=$ {random.int} dudu.bignumber=$ {random.long} dudu.uuid=$ {random.uuid} dudu.number.less.than.ten=$ {random.int (10)} dudu.number.in.range=$ {random.int [1024Volume 65536]} external configuration-Command Line Parameter configuration
Spring Boot is run based on the jar package, and the program packaged into jar can be run directly with the following command:
Java-jar xx.jar
The tomcat port number can be modified by the following command:
Java-jar xx.jar-- server.port=9090
As you can see, the two consecutive minus signs on the command line are identifiers for assigning attribute values in application.properties.
So java-jar xx.jar-- server.port=9090 is equivalent to adding the attribute server.port=9090 to application.properties.
If you are afraid that the command line is risky, you can use SpringApplication.setAddCommandLineProperties (false) to disable it.
In fact, Spring Boot applications can be set up in several ways, and Spring Boot can obtain attributes from multiple attribute sources, including the following:
The global properties of the development tool under the root directory (~ /. Spring-boot-devtools.properties when the development tool is activated).
The @ TestPropertySource annotation in the test.
The @ SpringBootTest#properties annotation feature in the test.
Command line argument
Attributes in SPRING_APPLICATION_JSON (inline JSON embedding in environment variables or system properties).
ServletConfig initialization parameters.
ServletContext initialization parameters.
JNDI attribute in java:comp/env
JVM system Properties
Operating system environment variable
Randomly generated attributes with random.* prefixes (you can apply them when setting other properties, such as ${random.long})
Application.properties or appliaction.yml files other than the application
Application.properties or appliaction.yml files packaged in the application
Attribute sources annotated through @ PropertySource
Default property (specified by SpringApplication.setDefaultProperties).
Here the list is sorted by group priority, that is, any attribute set in the high priority attribute source overrides the same attribute with low priority, and the column such as the command line attribute we mentioned above overrides the application.properties attribute.
Priority of the profile
The application.properties and application.yml files can be placed in the following four locations:
External, in the / congfig subdirectory relative to the application's running directory.
External, in the directory where the application is running
Built-in, in config package
Built-in, in Classpath root directory
Again, the list is sorted by priority, that is, application.properties under src/main/resources/config overrides the same attributes in application.properties under src/main/resources, as shown in the figure:
In addition, if you have both application.properties and application.yml at the same priority, the attributes in the application.yml will override the attributes in the application.properties.
Profile- multi-environment configuration
When an application needs to be deployed to different running environments, some configuration details are usually different. For example, the simplest log, the production log will set the log level to WARN or higher, and write the log to the log file. When developing, the log level needs to be DEBUG, and the log can be output to the console.
If we follow the previous practice of replacing the configuration file every time it is released, which is too troublesome, Spring Boot's Profile will provide us with a solution, and the command will be done with parameters.
Let's simulate it here, just simply modify the port to test
In Spring Boot, the multi-environment configuration file name needs to meet the format of application- {profile} .properties, where {profile} corresponds to your environment ID, such as:
Application-dev.properties: development environment
Application-prod.properties: production environment
To use the corresponding environment, you only need to use the spring.profiles.active attribute in application.properties. The value corresponds to the {profile} mentioned above, which means dev and prod.
Of course, you can also use the command line to start with the parameters:
Java-jar xxx.jar-- spring.profiles.active=dev
I add different port properties server.port to different environments, and then switch to use according to different spring.profiles.active specified. You can try it for yourself. No code will be posted here.
In addition to using the profile configuration file to partition and configure our environment variables, in the code, we can also directly use the @ Profile annotation to configure, such as database configuration, here we first define an interface
Public interface DBConnector {public void configure ();}
Define two implementation classes to implement it
/ * Test database * / @ Component@Profile ("testdb") public class TestDBConnector implements DBConnector {@ Override public void configure () {System.out.println ("testdb");}} / * production database * / @ Component@Profile ("devdb") public class DevDBConnector implements DBConnector {@ Override public void configure () {System.out.println ("devdb");}}
By activating which implementation class to use in the configuration file
Spring.profiles.active=testdb
And then you can use it like this.
@ RestController@RequestMapping ("/ task") public class TaskController {@ Autowired DBConnector connector; @ RequestMapping (value = {"/", "}) public String hellTask () {connector.configure (); / / finally print testdb return" hello task!! myage is "+ myage;}}
In addition to spring.profiles.active to activate one or more profile, you can also use spring.profiles.include to overlay profile
Spring.profiles.active: testdb spring.profiles.include: proddb,prodmq at this point, the study on "how to understand the configuration file application.properties in springboot" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.