Focus on Spring Boot+ micro services, mini programs, Flutter, Android, regularly share articles and video tutorials, reply to Java materials after attention, receive the learning dry goods carefully prepared for you!

Hello, everyone, I am “chasing dream snail”, you can reply “Java information” in the background of the public account to obtain the information of skill improvement, it is absolutely dry goods.

First knowledge of the Spring Boot framework

preface

(I). Spring Boot port configuration

(2). Use XML configuration

(3). Command line parameter configuration

(iv). General attribute configuration

5. Type safe configuration (based on Properties)

(6). Log configuration

7. Profile configuration



(I). Spring Boot port configuration



Spring Boot uses a global configuration file, application.properties or application.yml, in the SRC /main/resources directory or under /config in the classpath.

SpringBoot supports not only regular properties configuration files, but also configuration files in the YAML language, which is a data-centric language with object-oriented features when configuring data.


Application.properties is a common configuration file, and SpringBoot’s global configuration file is used to modify some of the default configuration values.


The following uses the default port and access path as an example: Change the default Tomcat port 8080 to 8081 and the default access path /hello to /springboot/hello. 1. Add configuration information to the configuration file application.properties

server.port=8081server.servlet.context-path=/springbootCopy the code

2, or add it in the configuration file application.yml

server:    port: 8081    contextPath: /springbootCopy the code


The first application. Properties configuration is used to illustrate the results of the adjustment:


(2). Use XML configuration

SpringBoot advocates zero configuration, which means no XML configuration. However, in projects, we will encounter special requirements that require XML configuration. In this case, you will have to add XML configuration, which can be loaded via @importResource provided by Spring

Examples are as follows:

@ImportResource({"classpath:some-context.xml"."classpath:another-context.xml"})Copy the code


(3). Command line parameter configuration

SpringBoot can be run based on jar packages and WAR packages. Jar programs can be run directly from the command line:

java -jar xxx.jarCopy the code

Of course, it is more convenient to change the Tomcat port from the command line:

java -jar xxx.jar --server.port=8081Copy the code

At this point your operating port can be changed at your discretion.


(iv). General attribute configuration

In a normal Spring environment, the way to inject values in the properties file is to specify the location of the properties file via @propertysource and then inject values via @Value, but in SpringBoot it is much easier. Just define the properties in the application.properties file and use @Value injection directly.

1. Add properties to application.properties

Game. Enterprise = Tencent Game. Name = Doudizhu gametrueCopy the code


2. Directly inject through @value in the interface class

@Value("${game.enterprise}")private String gameEnterprise; @Value("${game.name}")private String gameName; @Value("${game.taste}")private String taste;Copy the code

3. Modify the interface call function Test

@GetMapping(value = "/hello",produces = "text/plain; charset=UTF-8"//RequestMapping,GetMapping is an annotation that handles the requested address mapping. It can be used on a class or method with public StringTest() {return "First SpringBoot project, added to a single control class -- game company:"+gameEnterprise+"-- Game name:"+gameName                +"-- Are you interested?"+taste;    }Copy the code


The complete code is as follows:

package org.cxzc.myyoung.springboot_2; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; // @restController is equal to @Controller, @responseBody annotation, annotation up to the Controller class, which is equivalent to all methods in the entire class returning a JSON string // if you just use @restController annotation Contro Ller, the method of the Controller can't Return to the JSP page, or HTML, configure the view of the parser / / InternalResourceViewResolver doesn't work, the content of the Return of content in Return. @RestControllerpublic class HelloController { @Value("${game.enterprise}")    private String gameEnterprise;    @Value("${game.name}")    private String gameName;    @Value("${game.taste}")    private String taste;    @GetMapping(value = "/hello",produces = "text/plain; charset=UTF-8"//RequestMapping,GetMapping is an annotation that handles the requested address mapping. It can be used on a class or method with public StringTest() {return "First SpringBoot project, added to a single control class -- game company:"+gameEnterprise+"-- Game name:"+gameName                +"-- Are you interested?"+taste;    }}Copy the code


4. Access the browser to obtain the injection information

Some users add Chinese characters to the configuration file or output information in Chinese, which involves garbled characters in two places

1. Garbled output information. We need Chinese explanation when displaying the page, so garbled characters will appear as follows:

public String Test() {return "First SpringBoot project, added to a single control class -- game company:"+gameEnterprise+"-- Game name:"+gameName                +"-- Are you interested?"+taste;    }Copy the code

Solution: Request a character format in interface annotations

@GetMapping(value = "/hello",produces = "text/plain; charset=UTF-8")Copy the code

2, The application. Properties configuration file is set in Chinese, and garbled characters appear in the browser, as follows

Game. Enterprise = Tencent Game. Name = Doudizhu gametrueCopy the code

Workaround: Add properties to the configuration file application.properties

server.tomcat.uri-encoding=UTF-8spring.http.encoding.charset=UTF-8spring.http.encoding.enabled=truespring.http.encoding. force=truespring.messages.encoding=UTF-8Copy the code

Then go to File -> Settings -> Editor -> File Encodings in IntelliJ IDEA

Set Default encoding for Properties Files (*.properties) to UTF-8, Check the box before Transparent native-to- ASCII conversion.

The diagram below:

To this conventional attribute configuration small partners should be able to have a sense of achievement……



5. Type safe configuration (based on Properties)

Using @Value to inject each configuration would be very troublesome in the actual project development. After all, our configuration is usually multiple, so using the above method would require us to use @Value injection many times.

Of course, SpringBoot takes this into account and provides type-safe configuration by associating the Preporties property with a Bean and its properties via @ConfigurationProperties.

Examples are as follows:

1. Create the eat.properties file in the SRC /main/resources folder and add the property values


2. Create a type-safe Bean and inject the values in the properties file as follows:

package org.cxzc.myyoung.springboot_2; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; /** * @auther * @about public account program job * @content description information */@Component@ConfigurationProperties(prefix ="eat")@PropertySource("classpath:eat.properties")public class EatFood {    private String eatName;    private int eatprice;    public String getEatName() {        return eatName;    }    public void setEatName(String eatName) {        this.eatName = eatName;    }    public int getEatprice() {        return eatprice;    }    public void setEatprice(int eatprice) {        this.eatprice = eatprice;    }}Copy the code

Code explanation: ConfigurationProperties(prefix = “eat”) Specify the location of the file via @propertysource (before 1.4, specify the file location of the properties via location)

3. Inject beans in this configuration in the interface control class via @AutoWired

 @Autowired private EatFood eatFood;Copy the code

4. Add a path mapping

@GetMapping(value = "/prope",produces = "text/plain; charset=UTF-8")    public String Test2() {return "What do you like to eat?"+eatFood.getEatName()+"-- What's the price?"+eatFood.getEatprice();    }Copy the code

The code is as follows:

package org.cxzc.myyoung.springboot_2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; // @restController is equal to @Controller, @responseBody annotation, annotation up to the Controller class, which is equivalent to all methods in the entire class returning a JSON string // if you just use @restController annotation Contro Ller, the method of the Controller can't Return to the JSP page, or HTML, configure the view of the parser / / InternalResourceViewResolver doesn't work, the content of the Return of content in Return. @RestControllerpublic class HelloController { @Autowired private EatFood eatFood; @GetMapping(value ="/prope",produces = "text/plain; charset=UTF-8")    public String Test2() {return "What do you like to eat?"+eatFood.getEatName()+"-- What's the price?"+eatFood.getEatprice();    }}Copy the code



5. Running result


(6). Log configuration

SpringBoot supports JavaUtil Logging, Log4j, Log4j2, and Logback as Logging frameworks. Regardless of which Logging framework is used, SpringBoot is configured for console output and file output using the Logging framework.

By default, SpringBoot uses LogBack as the logging framework.

1. Configure log files

logging.file=d:/log/log.logCopy the code

2. Configure the log level (format: logging.level. package name = level).

logging.level.org.springframework.web=debugCopy the code

Complete configuration:

logging.file=d:/log/log.loglogging.level.org.springframework.web=debugCopy the code

After the log configuration is complete, the project is started and the corresponding log file is displayed in the configuration path.

7. Profile configuration

Profiles are used by SpringBoot to support different configurations for different environments. The global Profile configuration uses application-{Profile}. Properties, for example, application-dev.properties

Specify which configuration to use by setting spring.profiles.active=prod in application.properties.

Let’s take the configuration of the development and formal environments as an example: 1, use SRC /main/resources to define the Profile files for different environments, with the names application-pro.properties and application-dev.properties respectively. The former indicates the production configuration, while the latter indicates the development configuration, as follows:


Let’s add a startup port to two different files,

Properties = 8082server.port=80822, application-dev.properties = 8081server.port=8081Copy the code


Do this in the application.properties file.

spring.profiles.active=devCopy the code

Result: By default we run the project using dev’s configuration:


Active =pro if you want to switch to a production environment, you just need to change spring.profiles. Active =dev to spring.profiles. Active =pro.


Download address of this case:

Github.com/ProceduralZ…

Focus on Spring Boot+ micro services, mini programs, Flutter, Android, regularly share articles and video tutorials, reply to Java materials after attention, receive the learning dry goods carefully prepared for you!