spring boot basics May 3, 2018

The running class under the main package @SpringBootApplication This annotation is the core annotation, the source code is as follows
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME) 
@Documented 
@Inherited 
@SpringBootConfiguration 
@EnableAutoConfiguration @ComponentScan( excludeFilters = {@Filter( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class} )} ) public @interface SpringBootApplication{ }
3: Spring Boot configuration file,   global configuration file application.properties or application.yml
    Modify the access path:
The default port is 8080, I changed it to 8081, the default access path is http://localhost:8080 , I changed it to http://localhost:8081/helloboot
server.context-path=/helloboot
server.port=8081
    Set the Chinese encoding and add it directly in the configuration file
To set Chinese specifically, add the following code to application.properties:
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
    Then modify the return value in the controller to get the configured attribute value
The easy way is: Associate the properties property with a Bean
  1. Create a property's Bean.properties, and then enter the name directly. Properties
book.name=***
book.author=***
book.price=***
  • Create Book Bean and inject the values ​​in the properties file
@Component         //
@ConfigurationProperties(prefix = "book",locations = "classpath:book.properties") //prefix is ​​the prefix. locations is the location/
public class BookBean {
private String name; 
private String author;
private String price;
//Generate its get and set methods.
}
  • Add the following code to the Controller to inject the Bean:
  • @Autowired
    private BookBean bookBean;
  • Add path mapping:
  • @RequestMapping("/book")
    public String book() {
    return "Hello Spring Boot! The BookName is "+bookBean.getName()+";and Book Author is "+bookBean.getAuthor()+";and Book price is "+bookBean.getPrice();
    }
Log output and configuration, add dependencies

add dependencies

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId></dependency>
 
To customize the name of the setting file, set the logging.config option in the properties directly:
log configuration
Add the following code in application.properties
# Configure log output location
logging.file=/home/sang/workspace/log.log 
#Configure the log level.
logging.level.org.springframework.web=debug
Start hot deployment
Add the following configuration to 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>
<!-- Without this configuration, devtools will not take effect -->
<fork>true</fork>
</configuration>
</plugin>
</plugins></build>
 
Multi-environment configuration profiles.
Create three configuration files in the src/main/resources directory, and configure different information in the three files:
application-dev.properties: for the development environment
application-test.properties: for the test environment
application-prod.properties: for production environments
 
After configuring different information, configure it directly in application.properties:
spring.profiles.active=dev
#dev is the development environment, and dev can be modified to other environments
Among them, the name attribute 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 regarded as a switch for whether the corresponding springProfile in the log configuration file is valid. Create the logback-spring.xml file under src/main/resources with the following content
<?xml version="1.0" encoding="UTF-8"?><configuration>
<!-- file output format-->
<property name="PATTERN" value="%-12(%d{yyyy-MM-dd HH:mm:ss.SSS}) |-%-5level [%thread] %c [%L] -| %msg%n" />
<!-- test file path-->
<property name="TEST_FILE_PATH" value="d:/test.log" />
<!-- pro file path-->
<property name="PRO_FILE_PATH" value="/opt/test/log" />
 
<!-- Development Environment-->
<springProfile name="dev">
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${PATTERN}</pattern>
</encoder>
</appender>
<logger name="com.light.springboot" level="debug" />
<root level="info">
<appender-ref ref="CONSOLE" />
</root>
</springProfile>
 
<!-- Test environment -->
<springProfile name="test">
<!-- generate one file per day-->
<appender name="TEST-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- file path-->
<file>${TEST_FILE_PATH}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- filename-->
<fileNamePattern>${TEST_FILE_PATH}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- Maximum number of files saved in history-->
<MaxHistory>100</MaxHistory>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>${PATTERN}</pattern>
</layout>
</appender>
<root level="info">
<appender-ref ref="TEST-FILE" />
</root>
</springProfile>
 
<!-- Production Environment-->
<springProfile name="prod">
<appender name="PROD_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${PRO_FILE_PATH}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${PRO_FILE_PATH}/warn.%d{yyyy-MM-dd}.log</fileNamePattern>
<MaxHistory>100</MaxHistory>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>${PATTERN}</pattern>
</layout>
</appender>
<root level="warn">
<appender-ref ref="PROD_FILE" />
</root>
</springProfile></configuration>

There are two ways of log output (log4j and logback, logback is officially recommended)

  • Configure logback
  • Configure log4j2

Configure logback
Spring boot will load classpath:logback-spring.xml or classpath:logback-spring.groovy by default.
If you need to customize the file name, configure the logging.config option in application.properties. dmeo
 
# Indicates the configuration log output location,
logging.file=/home/sang/workspace/log.log
#Configure log level
Create a logback-spring.xml file under src/main/resources with the following content:
<?xml version="1.0" encoding="UTF-8"?><configuration>
<!-- file output format-->
<property name="PATTERN" value="%-12(%d{yyyy-MM-dd HH:mm:ss.SSS}) |-%-5level [%thread] %c [%L] -| %msg%n" />
<!-- test file path-->
<property name="TEST_FILE_PATH" value="d:/test.log" />
<!-- pro file path-->
<property name="PRO_FILE_PATH" value="/opt/test/log" />
 
<!-- Development Environment-->
<springProfile name="dev">
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${PATTERN}</pattern>
</encoder>
</appender>
<logger name="com.light.springboot" level="debug" />
<root level="info">
<appender-ref ref="CONSOLE" />
</root>
</springProfile>
 
<!-- Test environment -->
<springProfile name="test">
<!-- generate one file per day-->
<appender name="TEST-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- file path-->
<file>${TEST_FILE_PATH}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- filename-->
<fileNamePattern>${TEST_FILE_PATH}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- Maximum number of files saved in history-->
<MaxHistory>100</MaxHistory>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>${PATTERN}</pattern>
</layout>
</appender>
<root level="info">
<appender-ref ref="TEST-FILE" />
</root>
</springProfile>
 
<!-- Production Environment-->
<springProfile name="prod">
<appender name="PROD_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${PRO_FILE_PATH}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${PRO_FILE_PATH}/warn.%d{yyyy-MM-dd}.log</fileNamePattern>
<MaxHistory>100</MaxHistory>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>${PATTERN}</pattern>
</layout>
</appender>
<root level="warn">
<appender-ref ref="PROD_FILE" />
</root>
</springProfile></configuration>
The name attribute of the springProfile tag corresponds to the configuration of spring.profiles.active in application.properties.
Among them, starting the corresponding development environment is the relevant log configuration that takes effect.


 
 
 
 
 
 
 
 
 
 
  • Configure log4j2
 add dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId></dependency>
 
 
 
Spring boot will load classpath:log4j2.xml or classpath:log4j2-spring.xml by default.
If you customize the file name, you need to configure logging.config options in application.properties.
The log4j2.xml file content is as follows:
<?xml version="1.0" encoding="utf-8"?><configuration>
<properties>
<!-- file output format-->
<property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} |-%-5level [%thread] %c [%L] -| %msg%n</property>
</properties>
<appenders>
<Console name="CONSOLE" target="system_out">
<PatternLayout pattern="${PATTERN}" />
</Console>
</appenders>
<loggers>
<logger name="com.light.springboot" level="debug" />
<root level="info">
<appenderref ref="CONSOLE" />
</root>
</loggers></configuration>
Like logback, log4j2 cannot set configuration data of multiple environments in one file. It can only name three log files with different names, and configure logging.config options in development and testing environments respectively.
Another option is to set it directly in application-*.properties, log related configuration:
logging.config # Log configuration file path, such as classpath:logback-spring.xml logging.exception-conversion-word 
# Conversion word used when logging exceptions logging.file # The name of the file for logging, such as: test.log logging.level.*
# 日志映射,如:logging.level.root=WARN, logging.level.org.springframework.web=DEBUG  logging.path 
# Log file path, such as: d:/ logging.pattern.console 
# The log format output to the console, only the default logback setting is supported. logging.pattern.file 
# The format of the log output to the log file, only the default logback setting is supported. logging.pattern.level # The format used to render the log level, only the default logback setting is supported. logging.register-shutdown-hook# Register a shutdown hook for the logging system during initialization
 
 
Project packaging method 1: jar package generated by default. 2: By overriding the part in the run main method
  • Generate jar package
 
By default, after executing the package command through maven, a jar package will be generated, and the jar package will have a built-in tomcat container.
You can run the project through java -jar
  • Packaged into war file
Ideas:
1 Let the SpringbootApplication class inherit SpringBootServletInitializer and override the configure method,
2: Then modify the pom.xml file //<packaging>war</packaging>
code show as below
@SpringBootApplication
public class SpringbootApplication extends SpringBootServletInitializer
{
@Override 
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 
    return application.sources(SpringbootApplication.class);
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
    }
}
//Then modify the pom.xml file //<packaging>war</packaging>
 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325233099&siteId=291194637