Refinement Spring Boot 03:Spring Boot Configuration file and configuration management , And read the configuration file in three ways

Content abstract : In this paper, Spring Boot Configuration file and configuration management , And three ways to read configuration files , And code demonstration .

stay Spring Boot Before appearance , One Spring There are generally many configuration files in projects , For example, there are configurations and web Server related information web.xml, Have configuration Spring Its own variety application-xxx.xml, One copy xxx Corresponding Sping A function module of , for example MVC and Data Source, And third party plug-ins Such as log4j Etc . Besides , The application itself may also have multiple configuration files , Just counting the number of these configuration files makes people feel dizzy , Let alone manage and configure them .

Spring Boot The arrival of Technology , It greatly simplifies the management and reading of these configuration files . about Spring. Configuration information , Configuration information of the third-party framework it supports , Apply custom configuration information , All integrated in one In file , There may have been near 10 A new configuration file , Now only one is needed . Don't be like before , The configuration information is scattered in different configuration files of the application . This obviously greatly simplifies the management of configuration information , Of course, it also reduces the probability of error .

1、Web Server configuration

Spring Boot The default to start web Server is Tomcat, The port is 8080, The context is “/”. For these default settings , We can all be in Reconfigure .

We're in Add two lines of code to



【 chart 1 Set server properties 】

Press shortcut key Shift + F10 Run the program , Enter the original website http://localhost:8080/hello, Server not found . The reason is that we have used the above two lines of code to modify Tomcat Port number and application context . We can see the result by entering the following URL .


【 chart 2 Hello, Spring Boot】

2、 use Undertow Replace the default Tomcat The server

Spring Boot Default built-in web Server is Tomcat. in fact , It supports three nested web The server , The other two are Jetty and Undertow, and Undertow Best performance , You can set it to web The server , Replace the other two .

Spring Boot Of spring-boot-starter-web Nested by default Tomcat. When we change to something else web Server time , If replaced with Undertow, Need to put Tomcat To block out . meanwhile , It is also necessary to introduce corresponding web The server corresponds to starter.

Now we're trying to put web The server is switched to Undertow, Modify as follows pom.xml

【 chart 3 To configure Undertow 】

The switch found on the Internet web Most server solutions are as follows , But in IDEA Compile and run the program , It's always

Stubbornly use Tomcat, Instead of enabling Undertow. At this time, there is enough reason to suspect that this is IDEA Caused by cache problems , You need to refresh like this IDEA Of Maven project .

【 chart 4 IDEA Refresh Maven project 】

Refresh Maven After the project , And then use Maven To compile the program , Double click... As shown in the figure below install.

【 chart 5 Maven Install 】

After compiling , Press shortcut key Shift + F10 Run the program , You can see the log output display Undertow It's started successfully .

【 chart 6 Undertow Successful startup 】

3、 Read Spring Boot Configuration of

Can be read in the application Configuration file for , And get the configuration information , For application use . in fact Spring Boot Provides three ways to read configuration files .

The first 1 One way is through Environment class Of getPropery() Method reading .

The first 2 One way is through @Value Annotation to automatically inject attribute values .

The first 3 One way is to automatically inject a set of attributes into a configuration class .

We first in Add the following four lines of configuration , Then use three methods to read .

app.message1=Hi, Felix!

app.message2=You are really an IT expert.



Now modify HelloWorld Of sayHello Method , Use @Value Annotation method to read app.message1, use Enviornment.getProperty() Read app.message2, use @Autowired hold Environment Inject in , You can call its getProperty() The method . The code is as follows :

【 chart 7 Environment & @Value】

After starting the program , Successfully read the data of the configuration file in two ways , The output in the browser is as follows :

【 chart 8 Felix IT Expert】

The first 3 One way to read the configuration file is to automatically inject a set of attributes into a configuration class , In this case, you need to use annotations @ConfigurationProperties and @Configuration, We read... In this way app.num1 and app.num2 Value , And sum them , Then output the result . Or code .

【 chart 9 Configuration Properties 】

AppConfig Class uses two annotations @ConfigurationProperties and @Configuration, stay @ConfigurationProperties The parameter... Is entered in “app”, It's a property app.num1 and app.num2 The prefix of , As you can see from the following code AppConfig It's just an ordinary POJO file , It's just a note .

Next, let's look at how to use AppConfig This class . Now let's create a new summation controller SumController, Using annotations @Autowired hold AppConfig Automatically inject in , You can use it , Is it convenient 、 It's simple .

【 chart 10 Summation controller 】

Press Shift + F10 Start the program , Input Sum Method corresponding to url http://localhost:9090/home/sum, You can see the result .

【 chart 11 Summation result 】

Okay , The third chapter written by Feixian spacetime Spring Boot To this end , Welcome to forward and follow .

Enjoy coding.

Refinement Spring Boot 03:Spring Boot Configuration file and configuration management , And more articles about reading configuration files in three ways

  1. Spring Implement initialization and destruction bean Previous operations , Three ways

    About the spring   Container initialization bean There are three ways to define the operation before destruction : The first one is : adopt @PostConstruct and @PreDestroy Method Implement initialization and destruction bean Previous operations second ...

  2. java 4 There are two ways to read configuration files + Modify the configuration file

    Copyright notice : This article is an original blog article , No reprint without the permission of the blogger .   Catalog (?)[-] Mode 1 is adopted ServletContext To read a configuration file realpath And then read it through the file stream Mode 2 is adopted ResourceB ...

  3. 【spring Boot】spring boot Three ways to obtain resource files 【 In both cases 】

    Let me start with a statement ,springboot Get resource file , Need to see yes 1> from spring boot default Get... From the resource file 2> Or get from the customized resource file belt ...

  4. Spring note 03(Spring Three ways to create objects )

    1. There are three ways to create objects and bean Life cycle verification of : Animal Interface code : package cn.pb.dao; /** * Animal interface */ public interface Animal { // eat ...

  5. spring Study (03) And bean Three ways to instantiate

    bean There are three ways to instantiate stay spring There are three instantiations in bean The way : One . Instantiate with constructor :( One of the common methods used , a key ) Two . Instantiate using static factory methods : 3、 ... and . Use the example factory method to instantiate The first one is . Usage construction ...

  6. spring @Value Get the configuration file as null Several common ways

    The first way : Wrong attribute name , Not with @Value("${xxx}") Make a correspondence The second way : This class is not injected into spring bean In the container @Component ...

  7. 【Spring】 Of 【bean】 management (XML The configuration file )【Bean Three ways to instantiate 】

    Bean Three ways to instantiate explain : Creating an object through a configuration file is called Bean Instantiation . The first one is : Create with nonparametric construction of class ( a key ) Entity class package com.tyzr.ioc; public class User ...

  8. Spring in bean Three ways to instantiate

    I've had several blogs before Spring The framework , But at that time, we all used annotations to complete the injection , For specific partners, please refer to these blogs (Spring&SpringMVC Framework case ). So today I want to talk about how to pass xml with ...

  9. 【Java EE Study 52】【Spring The fourth day of study 】【Spring And JDBC】【JdbcTemplate Three ways to create 】【Spring Business management 】【 Transaction dbutils The rollback fails !!!??】

    One .JDBC Programming features Static code + Dynamic variables =JDBC Programming . Static code : For example, all database connection pools It's all done DataSource Interface , It's all done Connection Interface . Dynamic variables : user name . password . Connected database . ...

  10. Spring Three ways of dependency injection

    In the interpretation of the Spring Preparation before dependency injection : Download contains Spring Tools for jar Package compression package Unzip the downloaded Spring Compress package file After decompression, we'll see libs There are many... Under the folder jar package , And we just need one of them c ...

Random recommendation

  1. .NET 4.6.2 The official release brings a lot of features

    Although most people's attention is focused on .NET Core On , But with the original .NET Framework The work is still going on ..NET Framework 4.6.2 The official version has been released recently , The focus is on safety and WinForms/ ...

  2. SpringMVC The core distributor DispatcherServlet analysis [ With source code analysis ]

    Catalog Preface DispatcherServlet Initialization process DispatcherServlet Process request summary Reference material Preface SpringMVC It's the current mainstream Web MVC One of the frames . If some students don't like it ...

  3. mssql2000 ID number verification

    CREATE VIEW thisDate -- Return current date , Because it can't be used in custom functions GETDATE() AS ),) AS aDate )) /*mssql2000 Return value =0, ID card verification is correct 1: position ...

  4. redis linux Installation and simple cluster configuration

    Recently used due to project reasons redis, hold redis The installation and configuration of are recorded for easy viewing . 1. download Address   Use whatever version you need 2. Explain ...

  5. jquery Define table width

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " ...

  6. Hadoop: HDFS When formatting , appear &ldquo;ERROR namenode.NameNode: Cannot create directory /usr/hadoop/tmp/dfs/name/current&rdquo;

    as a result of No settings /usr/hadoop/tmp The permission of is not set , Change it to : chown –R hadoop:hadoop /usr/hadoop/tmp see :

  7. Solaris-[ODBC-ORACLE WP Driver] Some of the problems

    Make sure it's installed before ORACLE and ODBC,ODBC There are several problems connecting to the database One . land oracle And start the [[email protected]:/export]$su - oracle Oracle Corporat ...

  8. Java Enterprise wechat development _03_ Address book synchronization

    One . Main points of this section 1. Get the address book key Access method : Log in to enterprise wechat —> Management tools —> Address book synchronization assistant —> Turn on “API Interface synchronization ”  ; After opening , You can see the address book key , You can also set the address book API Authority : Read ...

  9. ELK Log collection

    The pain point of the current log Operation and maintenance to often log on to the server, take the log to the development . test Every time I go to the log after something goes wrong , You can't predict problems in advance through logs If it's a cluster service , Logs will be taken from multiple machines The logs made by developers are not standardized , There is no standard . The log directory is not ...

  10. Yii2 To configure Nginx Pseudostatic

    Mainly check the following codes : location / { # Redirect everything that isn't a real file to index.php try_files $uri $uri ...