The Magic of SpringBook Development Case

Keywords: Spring Thymeleaf JSON Tomcat

Programmers have a natural curiosity that guides our programming career. It's very interesting to write a few lines of code, load it into the computer and let it work according to your ideas. But as we develop more and more things, we get busier and busier, and this curiosity slowly fades. From time to time, we should challenge ourselves with some new ideas, keep our thoughts sharp and focused, and remind ourselves why we chose the road of barn farmer.

Version annotation

Little buddies may find that many of pom.xml has no version number, such as:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
</dependency>

In fact, we added the following configuration in the head:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/>
</parent>

spring-boot-starter-parent contains a large number of well-configured dependency management, so you don't need to write version numbers when adding these dependencies to your project

Hot Deployment

Method 1 adds spring loaded dependencies

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>springloaded</artifactId>
     <version>1.2.5.RELEASE</version>
</dependency>

Principle: Dynamic generation of classes or enhancement of existing classes based on ASM is realized. Each class modification is detected, and then new classes are generated and loaded. If you don't know what ASM is, you can Baidu JAVA-ASM.

Method 2 adds spring-boot-devtools dependencies

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
</dependency>

Principle: spring-boot-devtools is a module that serves developers. The most important function is to automatically apply code changes to the latest App. The principle is to restart the application after discovering that the code has changed, but faster than restarting after manually stopping. Faster refers not to the saved manual operation time. The underlying principle is to use two ClassLoaders, one Classloader to load classes that will not change (third-party Jar packages), and the other ClassLoader to load classes that will change, called restart ClassLoader, so that when code changes, the original restart ClassLoader is discarded and a restart ClassLoader is recreated, because fewer classes need to be loaded. To achieve a faster restart time (less than 5 seconds).

configuration file

In spring boot, there are two ways to implement file configuration, application.properties and application.yml. You may be familiar with properties, while another YML is based on YAML, which is a more intuitive form of expression than JSON (json multi-level {and [will be confused]), and is easier to detect errors and describe relationships on display. Because you don't need a professional tool to check for correctness.

Next, let's take server as an example to show the difference between the two.

application.properties

server.context-path=/springboot
server.port=8080
server.session-timeout=60
server.address=192.168.1.66

server.tomcat.max-threads=300
server.tomcat.uri-encoding=UTF-8

application.yml

server:
    context-path: /springboot
    port: 8080
    session-timeout: 60
    address: 192.168.1.66
    tomcat:
      max-threads: 300
      uri-encoding: UTF-8
logging:
    level:
      root: INFO

YML natural tree structure, clear at a glance, strong sense of hierarchy, whether you are blind. Of course, when using yml, it is important to note that the level interval must be a space, not a TAB, and that there must be a space between the value of the attribute name and the colon.

Deployment environment

Development Environment
application-dev.properties

Test environment
application-test.properties

Production Environment
application-prod.properties

So how do you define which configuration file to use?
The main configuration file, application.yml, is configured as follows:

spring:
  profiles:
    active: dev

Property Configuration

How do I get the attributes in the configuration file in the code? spring-boot provides us with a way to do this by simply using the @Value annotation.

@Value("${spring.mail.username}")
public String USER_NAME;

thymeleaf template

By default, thymeleaf is very strict with the content of html, for example, if there are fewer final label closures /, it will report an error and go to the error page.

#Ignore thymeleaf's rigorous verification
spring.thymeleaf.mode=LEGACYHTML5

#The development phase is set to false to facilitate debugging
spring.devtools.livereload.enabled=true
spring.thymeleaf.cache=false
spring.thymeleaf.cache-period=0
spring.thymeleaf.template.cache=false

Static resources

Where should static resources (JS, pictures) and so on be placed in Spring Boot?

Spring Boot can greatly simplify the reasons for WEB application development. The most important thing is to follow the basic principle of "convention is better than configuration". Spring Boot's default configuration of static resources has fully met the needs of most Web applications. There's no need to go through complicated customizations, just use Spring Boot's convention.

Under the Maven Project Directory, all static resources are placed in the src/main/resource directory, with the following structure:

src/main/resource
          |__________static
                        |_________js
                        |_________images
                        |_________css
                 .....

For example, we introduce the following css:

<link rel="stylesheet" th:href="@{css/alipay.css}" />

Customize static resources

Configuration through configuration files

Configuration in application.properties (or. yml)

# Static File Request Matching
spring.mvc.static-path-pattern=/**
# Modify the default static addressable resource directory using comma delimitation
spring.resources.static-locations = classpath:/templates/,classpath:/resources/,classpath:/static/

Through code configuration

@EnableAutoConfiguration
@ComponentScan(basePackages = { "com.itstyle.modules" })
public class Application extends WebMvcConfigurerAdapter {
    private static final Logger logger = Logger.getLogger(Application.class);
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/cert/**").addResourceLocations(
                "classpath:/cert/");
        super.addResourceHandlers(registry);
        logger.info("Custom static resource directory");
    }

    public static void main(String[] args) throws InterruptedException,
            IOException {
        SpringApplication.run(Application.class, args);
        logger.info("Payment Project Start ");
    }

}

File operation

get files

File file = ResourceUtils.getFile("classpath:cert/readme.txt");

Getting Path

ClassUtils.getDefaultClassLoader().getResource("cert").getPath()

What is the difference between Controller and RestController?

Official documents:
@RestController is a stereotype annotation that combines @ResponseBody and @Controller.
Intend:
@ The RestController annotation is equivalent to @ResponseBody+@Controller combined.

1) If you just annotate Controller with @RestController, the method in Controller cannot return to the jsp page. The configurable view resolver, Internal ResourceViewResolver, does not work. The content returned is the content in Return.
For example, if you should have gone to the success.jsp page, it will show success.

2) If you need to return to the specified page, you need to use @Controller with the view parser Internal ResourceViewResolver.
3) If you need to return JSON, XML or custom mediaType content to the page, you need to add the @ResponseBody annotation to the corresponding method.

Author: Xiao Qi

Source: https://blog.52itstyle.com

Copyright of this article belongs to the author and Yunqi Community. Reprint is welcome, but this statement must be retained without the author's consent. It is clearly given on the article page. If there is any problem, you can email it.( 345849402@qq.com ) Consultation.

Posted by mtmosier on Sat, 08 Jun 2019 12:08:25 -0700