Spring Boot Starter Basics (i)

Source: Internet
Author: User

Original address: Spring Boot Starter Basics (i)
Blog Address: http://www.extlight.com

First, preface

Spring Boot is a new framework provided by the Pivotal team designed to simplify the initial setup and development of new Spring applications. The framework uses a specific approach to configuration, which eliminates the need for developers to define boilerplate configurations.

This series is based on Quick start and can be read as a tool booklet

Second, the environment construction

Create a MAVEN project with a directory structure such as:

2.1 Adding dependencies

To create a MAVEN project, add the following dependencies in the Pom.xml file:

<!--define public resource versions --<parent>    <groupId>Org.springframework.boot</groupId>    <artifactId>Spring-boot-starter-parent</artifactId>    <version>1.5.6.RELEASE</version>    <relativepath /> </parent><properties>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>    <java.version>1.8</java.version></properties><dependencies>    <!--The parent is introduced, so there is no need to specify a version--    <!--contains jar resources such as MVC,AOP -    <dependency>        <groupId>Org.springframework.boot</groupId>        <artifactId>Spring-boot-starter-web</artifactId>    </dependency></dependencies><build>    <plugins>        <plugin>            <groupId>Org.springframework.boot</groupId>            <artifactId>Spring-boot-maven-plugin</artifactId>        </plugin>    </plugins></build>
2.2 Creating directories and configuration Files

Create a directory of Src/main/resources source files and create folders for application.properties files, static, and templates in this directory.

Application.properties: Used to configure the configuration data required for the project to run.

Static: Used for the storage of resources, such as: CSS, JS, pictures and so on.

Templates: Used to store template files.

The directory structure is as follows:

2.3 Creating a Startup class

Under the Com.light.springboot package, create the startup class as follows:

/** 该注解指定项目为springboot,由此类当作程序入口 自动装配 web 依赖的环境 **/@SpringBootApplicationpublicclass SpringbootApplication {    publicstaticvoidmain(String[] args) {        SpringApplication.run(SpringbootApplication.class, args);    }}
2.4 Case Demo

Create the Com.light.springboot.controller package and create a controller class under the package, as follows:

@RestControllerpublicclass TestController {    @GetMapping("/helloworld")    publichelloworld() {        return"helloworld";    }}

In the Springbootapplication file, right-click Run as, Java application. When you see the word "Tomcat started on port (s): 8080 (http)", the description starts successfully.

Open the browser to access Http://localhost:8080/helloworld and the results are as follows:

The reader can use the STS development tool, which integrates plug-ins to create the Spingboot project directly, which automatically generates the necessary directory structure.

Third, hot deployment

When we modify the file and create the file, we need to restart the project. This frequent operation is a waste of time, and configuring a hot deployment allows the project to automatically load the changed files, eliminating the manual action.

Add the following configuration in the Pom.xml file:

<!--Hot deployment-->     <DEPENDENCY>  <GROUPID>  org.springframework.boot</GROUPID>  <ARTIFACTID>  spring-boot-devtools</ARTIFACTID>  <OPTIONAL>  true</OPTIONAL>  < Scope>  true</SCOPE>  </DEPENDENCY>   
<build>    <plugins>        <plugin>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-maven-plugin</artifactId>            <configuration>                <!-- 没有该配置,devtools 不生效 -->                <fork>true</fork>            </configuration>        </plugin>    </plugins></build>

After configuring the Pom.xml file, we launch the project, randomly create/modify a file and save it, we will find the console print Springboot reload the file information.

The demo diagram is as follows:

Four, multi-environment switch

Application.properties is the configuration information required for Springboot to run.

When we are in the development phase, we use our own machine to develop, test the test server testing, and use the official environment when the server is on line.

These three environments require different configuration information, and when we switch the environment to run the project, we need to manually modify the configuration information, which is very error-prone.

To address these issues, Springboot provides a multi-environment configuration mechanism that makes it very easy for developers to switch between different configuration environments as needed.

Create three configuration files under the Src/main/resources directory:

application-dev.properties:用于开发环境application-test.properties:用于测试环境application-prod.properties:用于生产环境

We can set different information in this three configuration file, application.properties Configure the public information.

Configure in Application.properties:

spring.profiles.active=dev

Indicates that the Application-dev.properties file configuration is activated, and springboot loads information that uses application.properties and application-dev.properties configuration files.

Similarly, the value of spring.profiles.active can be modified to test or PROD to achieve the purpose of switching the environment.

The demo diagram is as follows:

V. Configuration Log 5.1 configuration Logback (officially recommended) 5.1.1 Configuration log file

Spring boot will load Classpath:logback-spring.xml or Classpath:logback-spring.groovy by default.

If you need a custom file name, configure the Logging.config option in Application.properties.

Under Src/main/resources, create a logback-spring.xml file that reads as follows:

<?xmlVersion= "1.0" encoding= "UTF-8"?><configuration>    <!--file output format --    <propertyname="PATTERN"value="%-12 (%d{yyyy-mm-dd HH:mm:ss. SSS}) |-%-5level [%thread]%c [%l]-| %msg%n " />    <!--test file path --    <propertyname="Test_file_path"value="D:/test.log" />    <!--Pro file path --    <propertyname="Pro_file_path"value="/opt/test/log" />        <!--development environment --    <springprofilename="Dev">        <appendername="CONSOLE"class="Ch.qos.logback.core.ConsoleAppender">            <encoder>                <pattern>${pattern}</pattern>            </encoder>        </appender>        <loggername="Com.light.springboot"level="Debug" />        <rootlevel="Info">            <appender-refref="CONSOLE" />        </root>    </springProfile>        <!--test environment --    <springprofilename="Test">        <!--produce one file per day --        <appendername="Test-file"class="Ch.qos.logback.core.rolling.RollingFileAppender">            <!--file path --            <file>${test_file_path}</file>            <rollingpolicyclass="Ch.qos.logback.core.rolling.TimeBasedRollingPolicy">                <!--file name --                <fileNamePattern>${test_file_path}/info.%d{yyyy-mm-dd}.log</fileNamePattern>                <!--file maximum saved history -                <MaxHistory>100</MaxHistory>            </rollingPolicy>            <layoutclass="Ch.qos.logback.classic.PatternLayout">                <pattern>${pattern}</pattern>            </layout>        </appender>        <rootlevel="Info">            <appender-refref="Test-file" />        </root>    </springProfile>        <!--production environment --    <springprofilename="prod">        <appendername="Prod_file"class="Ch.qos.logback.core.rolling.RollingFileAppender">            <file>${pro_file_path}</file>            <rollingpolicyclass="Ch.qos.logback.core.rolling.TimeBasedRollingPolicy">                <fileNamePattern>${pro_file_path}/warn.%d{yyyy-mm-dd}.log</fileNamePattern>                <MaxHistory>100</MaxHistory>            </rollingPolicy>            <layoutclass="Ch.qos.logback.classic.PatternLayout">                <pattern>${pattern}</pattern>            </layout>        </appender>        <rootlevel="Warn">            <appender-refref="Prod_file" />        </root>    </springProfile></configuration>

Where the Name property of the Springprofile tag corresponds to the configuration of spring.profiles.active in Application.properties.

That is, the value of spring.profiles.active can be seen as a switch in which the corresponding springprofile in the log configuration file is in effect.

5.2 Configuring log4j25.2.1 Add dependency
<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-log4j2</artifactId></dependency>
5.2.2 Configuration log file

Spring boot will load Classpath:log4j2.xml or classpath:log4j2-spring.xml by default.

If you need a custom file name, configure the Logging.config option in Application.properties.

The contents of the Log4j2.xml file are as follows:

<?xmlVersion= "1.0" encoding= "Utf-8"?><configuration>    <properties>        <!--file output format --        <propertyname="PATTERN">%d{yyyy-mm-dd HH:mm:ss. SSS} |-%-5level [%thread]%c [%l]-| %msg%n</property>    </properties>    <appenders>        <consolename="CONSOLE"target="System_out">            <patternlayoutpattern="${pattern}" />        </Console>    </appenders>    <loggers>        <loggername="Com.light.springboot"level="Debug" />        <rootlevel="Info">            <appenderrefref="CONSOLE" />        </root>    </loggers></configuration>

LOG4J2 cannot set configuration data for multiple environments in a file like Logback, only 3 log files with different names can be named, configured in Application-dev,application-test and Application-prod, respectively Logging.config option.

In addition to setting parameters in the log configuration file, you can also set the log-related configuration in application-*.properties:

logging.config                    # 日志配置文件路径,如 classpath:logback-spring.xmllogging.exception-conversion-word # 记录异常时使用的转换词logging.file                      # 记录日志的文件名称,如:test.loglogging.level.*                   # 日志映射,如:logging.level.root=WARN,logging.level.org.springframework.web=DEBUGlogging.path                      # 记录日志的文件路径,如:d:/logging.pattern.console           # 向控制台输出的日志格式,只支持默认的 logback 设置。logging.pattern.file              # 向记录日志文件输出的日志格式,只支持默认的 logback 设置。logging.pattern.level             # 用于呈现日志级别的格式,只支持默认的 logback 设置。logging.register-shutdown-hook    # 初始化时为日志系统注册一个关闭钩子
Six, packaging run

There are two forms of packaging: jar and war.

6.1 Packaged into an executable jar package

By default, when the package command is executed through MAVEN, the jar is generated and the jar package has a Tomcat container built into it, so we can run the project through Java-jar, such as:

6.2 Packaged into a deployed war package

Let the Springbootapplication class inherit Springbootservletinitializer and rewrite the Configure method, as follows:

@SpringBootApplicationpublicclassextends SpringBootServletInitializer {    @Override    protectedconfigure(SpringApplicationBuilder application) {        return application.sources(SpringbootApplication.class);    }    publicstaticvoidmain(String[] args) {        SpringApplication.run(SpringbootApplication.class, args);    }}

Modify the Pom.xml file to change the jar to war, as follows:

<packaging>war</packaging>

After the package is successful, deploy the war package to the Tomcat container to run.

Vii. references
    • Https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/html/Official documents

Spring Boot Starter Basics (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.