Spring Boot Learning Record (i) – Environment building
tags (space delimited): Spring-boot
Recently take advantage of busy hours to learn spring-boot, record the learning process, and finally intend to combat an API management platform, the following start environment configuration.
1. Engineering structure
Using MAVEN to build a common structure , because spring-boot embedded tomcat, so packaging only needs to be packaged into a jar to run directly, so it is not the same as before the establishment of the Web program, the directory is as follows, the class can be set up in the first place:
2. Introducing MAVEN Dependencies
According to the official tutorial, the direct introduction of the parent can be used spring-boot to say goodbye to the previous spring tedious dependency configuration. Add the following configuration to the Pom.xml:
<parent> <groupId>Org.springframework.boot</groupId> <artifactid>Spring-boot-starter-parent</artifactid> <version>1.4.0.RELEASE</version></Parent><dependencies> <dependency> <groupId>Org.springframework.boot</groupId> <artifactid>Spring-boot-starter-web</artifactid> </Dependency></dependencies>
3. Write Demo
1. Writing entity Classes demoentity
/** * @author Niu Li * @date 2016/8/9 */publicclass DemoEntity { private String id; private String username; private String password; //省略set和get方法}
2. Write controller Hellocontroller, return JSON type
/** * @author Niu Li * @date 2016/8/9 * *@Controller Public class hellocontroller { /** * Test Hello * @return */ @RequestMapping(Value ="/hello", method = Requestmethod.get) Public@ResponseBody demoentityHello() {demoentity entity =NewDemoentity (); Entity.setid ("1"); Entity.setusername ("Niuli"); Entity.setpassword ("123456");returnEntity }}
3. Writing the launch portal
Since it is a jar executor, a main function is required as the start-up entry and the following code is added to the Application.java:
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * 默认启动类 */@SpringBootApplicationpublicclass Application{ publicstaticvoidmain( String[] args ) { SpringApplication.run(Application.class, args); }}
4. Test access
The Spring-boot is started on port 8080 by default and is directly accessible to the address:
4. Configure Logger
1.spring-boot log output By default is a colorful form, depending on your computer support is not supported to judge, of course, can also be configured in the Application.properties
spring.output.ansi.enabled
Never: Disable ansi-colored output (default)
DETECT: Check whether the terminal supports ANSI, and then use color output (recommended)
Always: Use ansi-colored format output, if the terminal is not supported, there will be a lot of interference information, not recommended to use
2.spring-boot Displays the info level and more logs by default, you can use the
logging.level.root = debug//或者debug=true
You can use the custom level for your project
logging.level.cn.mrdear=debug
In this case, declare that your own package of logs debug and the above level will be output.
3. Using Logger
Spring-boot automatically introduces the use of SLF4J and Logback, and the use of logs does not need to be introduced into the package yourself. Modify the controller as follows:
Importcn.mrdear.entity.DemoEntity;ImportOrg.slf4j.Logger;ImportOrg.slf4j.LoggerFactory;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.bind.annotation.ResponseBody;/** * @author Niu Li * @date 2016/8/9 * *@Controller Public class hellocontroller { PrivateLogger Logger = Loggerfactory.getlogger (Hellocontroller.class);/** * Test Hello * @return */ @RequestMapping(Value ="/hello", method = Requestmethod.get) Public@ResponseBody demoentityHello() {demoentity entity =NewDemoentity (); Entity.setid ("1"); Entity.setusername ("Niuli"); Entity.setpassword ("123456"); Logger.debug ("This is the debug message."); Logger.info ("This is info info"); Logger.warn ("This is warn information."); Logger.error ("This is the error message");returnEntity }}
4. Write log file
You need to configure Logging.file or Logging.path properties in Application.properties
Logging.file, the settings file can be either an absolute path or a relative path. such as: Logging.file=my.log
Logging.path, sets the directory where the Spring.log file is created and writes the contents of the log, such as: Logging.path=/var/log
* Log files will be truncated at 10Mb, resulting in a new log file with the default level: ERROR, WARN, INFO *
5. Custom Configuration
Spring supports log custom configuration, you only need to put the corresponding log configuration file in the Classpath directory, you can overwrite the configuration of the point Spring-boot itself, of course, the name should follow the following specifications:
logback:logback-spring Span class= "hljs-built_in". xml , Logback-spring Groovy, Logback xml , Logback Groovylog4j:log4j-spring Properties, Log4j-spring xml , Log4j Properties, Log4j xml Log4j2:log4j2-spring xml , Log4j2 xml
The replacement configuration is identical to the previous configuration logger.
5. Custom JSON Parser
Bloggers like to use the Fastjson as a JSON parser because it's easy.
The principle is to replace it with spring HttpMessageConverters
, where you inject your own converter.
First introduce Fastjson dependency:
<!--fast json start--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.14</version> </dependency> <!--fast json end-->
Build Webmessageconvert.java under the Conf package
ImportCom.alibaba.fastjson.serializer.SerializerFeature;ImportCom.alibaba.fastjson.support.config.FastJsonConfig;ImportCom.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;ImportOrg.springframework.boot.autoconfigure.web.HttpMessageConverters;ImportOrg.springframework.context.annotation.Bean;ImportOrg.springframework.context.annotation.Configuration;ImportOrg.springframework.http.converter.HttpMessageConverter;/** * Use Fastjson as a message converter * @author Niu Li * @date 2016/8/9 */@Configuration Public class webmessageconvert { /** * Use bean injection to make it effective, verify that you use Fastjson's * annotation @jsonfield (serialize = False) in the Entity field, and that the converted information does not contain the field, then success * @return * / @Bean PublicHttpmessageconverterscustomconverters() {Fastjsonhttpmessageconverter Fastconverter =NewFastjsonhttpmessageconverter (); Fastjsonconfig Fastjsonconfig =NewFastjsonconfig (); Fastjsonconfig.setserializerfeatures (Serializerfeature.prettyformat); Fastconverter.setfastjsonconfig (Fastjsonconfig);return NewHttpmessageconverters ((httpmessageconverter<?>) fastconverter); }}
6.banner replacement
Banner is the message from Spring-boot when it starts.
The replacement is simple to create a banner.txt in the Classpath directory, so that Spring-boot will automatically read the configuration and then output. If you want to turn it off, configure it in application:
spring.main.banner-mode=off
Can.
Spring Boot Learning Record (i)--environment construction