Spring boot development of the relentless flow of water (ii)

Source: Internet
Author: User
Tags log log java util

http://my.oschina.net/u/1027043/blog/406558



The last chapter of a very simple entry-level spring boot example, no technical content, but, in fact, learn anything as long as the first breakthrough, the next thing is good to do, the most afraid of what? I think there is no way to do one thing, no place to start, and when you find this feeling, you can be very happy to explore the pursuit of a very strong desire to explore something, this mysterious and mysterious feeling is what? Recall:

(1) When you put the first example of the Hello World of some programming language, successfully run in an IDE
(2) When you first started from your hometown and arrived at a place you've never been before.
(3) When you successfully completed the first online shopping

All the unrelated things between, in fact, have a similar learning process, it is so-called comprehend by analogy, million-law return to the Pope!

About Spring boot this piece, actually involved in the content is very many and very flexible, the module used in the project is only the tip of the iceberg, it is impossible to completely cover all the relevant modules, completely for the project and with the technology, not for technology and the birth of this project, so this record of experience, is completely project-related, not spring boot a learning tutorial, this, I hope you crossing understand, if you want to specialize in learning Spring boot, recommended click on the official website more detailed tutorial
A project is made up of a variety of different levels of technology, so the scatter fairy will not only write about the spring boot aspect, although spring boot is the main line. In most cases, there are many different technologies that can be combined to create the optimal architecture, only by playing their strengths.

Well, say a little more nonsense, below is a look at a few of the spring boot Knowledge Points:

(i) A maven+spring Boot Project basic Package structure form
(ii) A simple integrated security control in the Spring boot project
(ii) How to record log logs in spring boot
(iv) Introduction of several common annotations in Spring boot

OK, let's get started:

(a) Look first, the official website gives a simple package structure composed of:

Java code
  1. Com
  2. +-Example
  3. +-MyProject
  4. +-Application.java
  5. |
  6. +-Domain
  7. | +-Customer.java
  8. | +-Customerrepository.java
  9. |
  10. +-Service
  11. | +-Customerservice.java
  12. |
  13. +-Web
  14. +-Customercontroller.java



Then, look at the project structure of the actual work of the scattered fairy:






The following are the areas to note:
1, in the first layer under the Src/main/java package, it is necessary to put a main starting class containing the main method, and there can be only one main method, if the other main method, when using Maven compiled packaging, will be reported compile errors, of course, in src/test/ There can be multiple under the Java package, but it is advisable to use JUnit for unit testing.

When this main method starts, an inline tomcat or jetty container is started, and then all the classes or resource files that need to be loaded or scanned are loaded. In the previous blog, scattered cents in order to test convenience, is directly in the current Conroller, started a test service, this is suitable for individual debugging, if the startup method in the production environment, it is said in front of the Java package, in the root directory to create a Main method class, responsible for starting all resources.

In this example, the main code of the scatter fairy is as follows:

Java code
  1. Package com.dhgate.rate;
  2. Import org.springframework.boot.SpringApplication;
  3. Import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  4. Import Org.springframework.context.annotation.ComponentScan;
  5. Import org.springframework.context.annotation.Configuration;
  6. @Configuration//Configuration control
  7. @EnableAutoConfiguration//Enable automatic configuration
  8. @ComponentScan//Component Scan
  9. public class Applicationmain {
  10. public static void Main (string[] args) throws Exception {
  11. The only entry to start the Spring boot project
  12. Springapplication.run (Applicationmain.class, args);
  13. }
  14. }




2, under the Src/main/resource directory, is to place some configuration files, or template support files, such as Jsp,velocity,freemaker, which is more commonly used or important one file, is the spring Boot Centralized configuration file application.properties This file, which gives most of the other components, provides a centrally managed and configured hub, including security controls, Redis,solr,mangodb connection information, and database connection pool, container port number, jmx,j Ava Mail, dynamic templates, and more. In addition to this directory, the default is to access static resources, such as our css,js, or some third-party reference files.

(b) Regarding the simple secure access control in spring boot configuration, this is a very container, and we just need to do the following two steps.
1, in the Pom file, introduce Spring-boot-starter-security's maven dependency.

XML code
    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-security</artifactId>
    4. </dependency>



2, in Application.properties, configure the user name and password for access

Java code
    1. #用户名 Password Configuration
    2. Security.user.name=admin
    3. Security.user.password=test



Again, when the link is accessed, the following will appear, blocking the page, on behalf of the configuration success:





Of course this is just, a primary configuration, more complex configuration, can be divided into roles, in the control range, to intercept the method level of permission control.

(c) The importance of logging, it goes without saying, Spring boot supports most log configurations, including:
(1) Java Util logging
(2) log4j
(3) Log4j2
(4) Logbak
By default, spring Boot chooses logback as the carrier for logging, and of course it needs to rely on Commons Logging, Java Util Logging, log4j or slf4j to work properly, I believe most of the students are choosing to use Log4j.properties as our log configuration and management, but the San Xian has not tested the integration successfully in spring boot, so we discard the use of log4j.properties as a log carrier, but chose spring Boot recommended Logbak As a log configuration file, after the use of the feeling is also good.

Steps to use:

1, copy the logbak.xml to the root directory under the resource directory, and then in Logbak.xml, configure the relevant log generation rules, log level, and log path, the character encoding set of logs, this is very important, because it was just beginning to use this log logger to run the information, it is found that it does not support Chinese L OG, later by the name of the search, you need to configure the relevant log code to correctly record the corresponding information. A common configuration is as follows:

XML code
  1. <!--logback configuration. See Http://logback.qos.ch/manual/index.html--
  2. <configuration scan= "true" scanperiod= "ten Seconds" >
  3. <!--Simple file output--
  4. <appender name= "FILE" class= "Ch.qos.logback.core.rolling.RollingFileAppender" >
  5. <!--encoder defaults to Ch.qos.logback.classic.encoder.PatternLayoutEncoder-
  6. <encoder>
  7. <pattern>
  8. [%-5level] [%date{yyyy-mm-dd HH:mm:ss}]%logger{96} [%line]-%msg%n
  9. </pattern>
  10. <charset>UTF-8</charset> <!--here to set the character set--
  11. </encoder>
  12. <rollingpolicy class= "Ch.qos.logback.core.rolling.TimeBasedRollingPolicy" >
  13. <!--rollover daily The directory generated by the configuration log and the rules for generating the file name--
  14. <fileNamePattern>logs/mylog-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
  15. <timebasedfilenamingandtriggeringpolicy
  16. class= "Ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP" >
  17. <!--or whenever the file size reaches
  18. <maxfilesize>64 mb</maxfilesize>
  19. </timeBasedFileNamingAndTriggeringPolicy>
  20. </rollingPolicy>
  21. <filter class= "Ch.qos.logback.classic.filter.ThresholdFilter" >
  22. <level>DEBUG</level>
  23. </filter>
  24. <!--safely log to the same file from multiple JVMs. Degrades performance! -
  25. <prudent>true</prudent>
  26. </appender>
  27. <!--Console output--
  28. <appender name= "STDOUT" class= "Ch.qos.logback.core.ConsoleAppender" >
  29. <!--encoder defaults to Ch.qos.logback.classic.encoder.PatternLayoutEncoder-
  30. <encoder>
  31. <pattern>
  32. [%-5level] [%date{yyyy-mm-dd HH:mm:ss}]%logger{96} [%line]-%msg%n
  33. </pattern>
  34. <charset>GBK</charset> <!--here to set the character set--
  35. </encoder>
  36. <!--only log level WARN and above-
  37. <filter class= "Ch.qos.logback.classic.filter.ThresholdFilter" >
  38. <level>WARN</level>
  39. </filter>
  40. </appender>
  41. <!--Enable FILE and STDOUT appenders for all log messages.
  42. By default with log at level INFO and above. -
  43. <root level= "INFO" >
  44. <appender-ref ref= "FILE"/>
  45. <appender-ref ref= "STDOUT"/>
  46. </root>
  47. <!--for loggers in the these namespaces, and log at all levels. -
  48. <logger name= "Pedestal" level= "all"/>
  49. <logger name= "Hammock-cafe" level= "All"/>
  50. <logger name= "User" level= "all"/>
  51. </configuration>




2, in Application.properties, specify the load path of the log file, and the common log log level has been configured:

Java code
    1. #指定log的配置文件, and record the log level of spring boot
    2. Logging.config=logback.xml
    3. Logging.level.org.springframework.web:INFO





(iv) Introduction of several commonly used annotations in spring boot, most of which are annotations from spring MVC, which are typically used at frequencies above 90%.

(1) @RestController and @controller specify a class as annotations to the controller
(2) @RequestMapping Method-level mapping annotations, a small partner who has used spring MVC to be familiar with
(3) @EnableAutoConfiguration and @springbootapplication are class-level annotations, which are based on MAVEN-dependent jar-based guessing to complete the correct spring counterpart configuration. The spring MVC and Tomcat containers are automatically configured by default as long as the spring-boot-starter-web dependency is introduced
(4) @Configuration class-level annotations, generally this annotation, which we use to identify the class where the Main method resides
(5) @ComponentScan class-level annotations, automatic scan loading all spring components, including bean injection, are typically used on the class where the Main method resides
(6) @ImportResource class level annotations, when we have to use an XML configuration, use @importresource and @configuration to identify the class of this file resource.
(7) @Autowired annotations, typically combined with @componentscan annotations, to automatically inject a service or DAO-level bean
(8) @Component class-level annotations to identify a component, such as when I have customized a filter, the Spring boot will not be recognized correctly until this annotation is identified.



OK, this is the end of this tutorial, these are the basic knowledge of project engineering, to understand these, help us to quickly get started with a spring boot application.

The content of the next blog will be written:
(1) How to integrate the spring loaded framework in the Spring boot project to complete the module hot Load and code dynamic compilation, with this thing, our development efficiency will be more efficient, most of the time we changed the code of a class or method, there is no need to restart the application, Because spring loaded will periodically recompile and load the code.

(2) How to integrate velocity,spring boot in the Spring boot project supports a variety of template engines, including
1,freemarker
2,groovy
3,thymeleaf
4,velocity
5,jsp (Spring boot official not recommended)
We can choose our favorite engine according to the degree of familiarity.

Spring boot development of the relentless flow of water (ii)

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.