Spring Boot Concise Tutorial

Introduction

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 way to configure, so that developers no longer need to define boilerplate configuration. In this way, Spring Boot aims to be a leader in the booming field of rapid application development.

Official website address: http://projects.spring.io/spring-boot/

 

Build the spring boot project

The spring boot project example has been uploaded to the code cloud: https://gitee.com/imlichao/SpringBoot-example

 

1. Use maven to create a basic spring boot project

spring boot can be installed using Maven or Gradle. Since I am not very familiar with Gradle, I only introduce the maven installation method here.

In fact, we can create a new normal maven project, and then create it by adding spring boot dependencies to the pom file.

But maven provides us with a lot of project templates. Since so many templates are provided, why don't we use them? The following example will use the maven template to create a spring boot project directly.

# 构建maven项目(项目目录名称与artifactId所指定的名称一致)
mvn archetype:generate -D groupId=pub.imlichao -D artifactId=SpringBoot-example

# 选择模板(4号为基础spring boot模板)
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 1052: 4


Through the above command we have created a basic spring boot project

Of course, this project has built most of the structure for us. Of course, the content needs to be adjusted a little by ourselves before it can be used normally.

 

2. Adjust the pom file

Adjust spring boot version

The spring boot version in the template is often outdated. If we need to use a new version, we need to adjust it in the pom file.

Modify the spring boot version in the pom.xml file

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

Add freemaker dependency

This configuration is not necessary because I am used to using freemaker, so it is added here.

<dependencies>
     <!-- 增加freemarker依赖 -->
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-freemarker</artifactId>
     </dependency>
 </dependencies>

remove unnecessary dependencies

Remove the content that is not needed for this project, and the content to be removed varies from project to project

The final adjusted pom file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>pub.imlichao</groupId>
    <artifactId>SpringBoot-example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <!-- 继承Spring Boot-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
    </parent>

    <dependencies>
        <!-- 增加web项目依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 增加freemarker依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
    </dependencies>
    <!-- 打包成可执行的jar包 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

3. Adjust the configuration file

The application.properties configuration file is in the resources resource directory.

This example only needs the port number, so delete other configurations and add the port number configuration.

# Server HTTP port.
server.port=8090

 

4. Create business code and page code

Not sure why the template code is not executable, so delete the template code and write your own test code.

Business code class HelloController 

package pub.imlichao;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {
    @GetMapping(value = "/")
    public String hello(){
        return "/hello";
    }
}

freemaker page hello.ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello world</title>
</head>
<body>
<h1>hello world</h1>
</body>
</html>

 

5. The adjusted project structure

 

6. Start the execution

"C:\Program Files\Java\jdk1.8.0_65\bin\java" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:58673,suspend=y,server=n -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_65\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\rt.jar;D:\workspaces\SpringBoot-example\target\classes;C:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot-starter-web\1.5.7.RELEASE\spring-boot-starter-web-1.5.7.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot-starter\1.5.7.RELEASE\spring-boot-starter-1.5.7.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot\1.5.7.RELEASE\spring-boot-1.5.7.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\1.5.7.RELEASE\spring-boot-autoconfigure-1.5.7.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot-starter-logging\1.5.7.RELEASE\spring-boot-starter-logging-1.5.7.RELEASE.jar;C:\Users\Administrator\.m2\repository\ch\qos\logback\logback-classic\1.1.11\logback-classic-1.1.11.jar;C:\Users\Administrator\.m2\repository\ch\qos\logback\logback-core\1.1.11\logback-core-1.1.11.jar;C:\Users\Administrator\.m2\repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar;C:\Users\Administrator\.m2\repository\org\slf4j\jcl-over-slf4j\1.7.25\jcl-over-slf4j-1.7.25.jar;C:\Users\Administrator\.m2\repository\org\slf4j\jul-to-slf4j\1.7.25\jul-to-slf4j-1.7.25.jar;C:\Users\Administrator\.m2\repository\org\slf4j\log4j-over-slf4j\1.7.25\log4j-over-slf4j-1.7.25.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-core\4.3.11.RELEASE\spring-core-4.3.11.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\yaml\snakeyaml\1.17\snakeyaml-1.17.jar;C:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot-starter-tomcat\1.5.7.RELEASE\spring-boot-starter-tomcat-1.5.7.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\apache\tomcat\embed\tomcat-embed-core\8.5.20\tomcat-embed-core-8.5.20.jar;C:\Users\Administrator\.m2\repository\org\apache\tomcat\embed\tomcat-embed-el\8.5.20\tomcat-embed-el-8.5.20.jar;C:\Users\Administrator\.m2\repository\org\apache\tomcat\embed\tomcat-embed-websocket\8.5.20\tomcat-embed-websocket-8.5.20.jar;C:\Users\Administrator\.m2\repository\org\hibernate\hibernate-validator\5.3.5.Final\hibernate-validator-5.3.5.Final.jar;C:\Users\Administrator\.m2\repository\javax\validation\validation-api\1.1.0.Final\validation-api-1.1.0.Final.jar;C:\Users\Administrator\.m2\repository\org\jboss\logging\jboss-logging\3.3.1.Final\jboss-logging-3.3.1.Final.jar;C:\Users\Administrator\.m2\repository\com\fasterxml\classmate\1.3.4\classmate-1.3.4.jar;C:\Users\Administrator\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.8.10\jackson-databind-2.8.10.jar;C:\Users\Administrator\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.8.0\jackson-annotations-2.8.0.jar;C:\Users\Administrator\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.8.10\jackson-core-2.8.10.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-web\4.3.11.RELEASE\spring-web-4.3.11.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-aop\4.3.11.RELEASE\spring-aop-4.3.11.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-beans\4.3.11.RELEASE\spring-beans-4.3.11.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-context\4.3.11.RELEASE\spring-context-4.3.11.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-webmvc\4.3.11.RELEASE\spring-webmvc-4.3.11.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-expression\4.3.11.RELEASE\spring-expression-4.3.11.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot-starter-freemarker\1.5.7.RELEASE\spring-boot-starter-freemarker-1.5.7.RELEASE.jar;C:\Users\Administrator\.m2\repository\org\freemarker\freemarker\2.3.26-incubating\freemarker-2.3.26-incubating.jar;C:\Users\Administrator\.m2\repository\org\springframework\spring-context-support\4.3.11.RELEASE\spring-context-support-4.3.11.RELEASE.jar;D:\Program Files\IntelliJ IDEA Community Edition 2017.1.4\lib\idea_rt.jar" pub.imlichao.App
Connected to the target VM, address: '127.0.0.1:58673', transport: 'socket'

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.7.RELEASE)

2017-09-28 14:18:00.828  INFO 7444 --- [           main] pub.imlichao.App                         : Starting App on 7WLOAFTSGWIIGSD with PID 7444 (D:\workspaces\SpringBoot-example\target\classes started by Administrator in D:\workspaces\SpringBoot-example)
2017-09-28 14:18:00.832  INFO 7444 --- [           main] pub.imlichao.App                         : No active profile set, falling back to default profiles: default
2017-09-28 14:18:00.920  INFO 7444 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@68c72235: startup date [Thu Sep 28 14:18:00 CST 2017]; root of context hierarchy
2017-09-28 14:18:02.739  INFO 7444 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8090 (http)
2017-09-28 14:18:02.757  INFO 7444 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-09-28 14:18:02.758  INFO 7444 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.20
2017-09-28 14:18:02.911  INFO 7444 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-09-28 14:18:02.912  INFO 7444 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1996 ms
2017-09-28 14:18:03.082  INFO 7444 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-09-28 14:18:03.085  INFO 7444 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-28 14:18:03.086  INFO 7444 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-28 14:18:03.086  INFO 7444 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-28 14:18:03.086  INFO 7444 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-09-28 14:18:03.447  INFO 7444 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@68c72235: startup date [Thu Sep 28 14:18:00 CST 2017]; root of context hierarchy
2017-09-28 14:18:03.531  INFO 7444 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET]}" onto public java.lang.String pub.imlichao.HelloController.hello()
2017-09-28 14:18:03.534  INFO 7444 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-09-28 14:18:03.535  INFO 7444 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-09-28 14:18:03.575  INFO 7444 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-28 14:18:03.575  INFO 7444 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-28 14:18:03.625  INFO 7444 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-28 14:18:03.866  INFO 7444 --- [           main] o.s.w.s.v.f.FreeMarkerConfigurer         : ClassTemplateLoader for Spring macros added to FreeMarker configuration
2017-09-28 14:18:04.122  INFO 7444 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-09-28 14:18:04.214  INFO 7444 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8090 (http)
2017-09-28 14:18:04.222  INFO 7444 --- [           main] pub.imlichao.App                         : Started App in 3.775 seconds (JVM running for 4.304)

Project configuration

The spring boot project can easily configure the properties of the project in the configuration file. For example, in the above example, the port number is configured in the configuration file.

By default, the configuration file will be placed in the resources resource directory, named application.properties.

We may need to use different configurations in different environments, so we can create multiple configuration files and specify the configuration file to be used when the project starts. For example: the configuration file is named application-test.properties as the configuration of the test environment, and the startup parameter is added --spring.profiles.active=test . The project will start using the application-test.properties configuration file.

Some commonly used configurations are described below. For more configurations, please refer to the official documentation:

https://docs.spring.io/spring-boot/docs/1.5.7.RELEASE/reference/htmlsingle/#appendix

server.port=8080 #项目端口号
management.port=8081 #项目管理端口号。不配置时默认与server.port一致。例如使用actuator时就要访问此端口

server.tomcat.max-threads=500 #tomcat最大线程数
server.tomcat.min-spare-threads=25 #tomcat最小线程数
server.tomcat.uri-encoding=UTF-8 #tomcat URI字符编码
server.tomcat.accept-count=100 #tomcat最大等待线程数

server.compression.enabled=true #是否对请求响应进行gzip压缩。
server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json,application/xml #需要压缩的响应类型。

spring.datasource.url=jdbc:mysql://rm-2ze4k2hch0pa4ie75.mysql.rds.aliyuncs.com:3306/mfqy-production?zeroDateTimeBehavior=convertToNull #数据库连接URL
spring.datasource.username=admin #数据库连接用户名
spring.datasource.password=111111 #数据库连接密码
spring.datasource.driverClassName=com.mysql.jdbc.Driver #数据库驱动类名称

spring.jpa.generate-ddl=true #是否使用hibernate hbm2ddl控制数据库
spring.jpa.hibernate.ddl-auto=update #hbm2ddl自动控制数据库类型 (validate | update | create | create-drop)
spring.jpa.showSql=false #是否记录sql日志

 

 

Common Notes

@SpringBootApplication

Using this annotation is equivalent to adding three annotations @Configuration, @EnableAutoConfiguration and @ComponentScan at the same time

@SpringBootApplication // 包含了 @Configuration @EnableAutoConfiguration @ComponentScan 三个注解
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

 

@Configuration

This annotation declares that the current class is a java-style configuration file class. XML configuration classes are often used in early projects, and we need to use this method in spring boot.

There is no substantial difference between the two methods, but the writing method is different. After mastering the rules, we can "translate" the configuration file in XML form into java form.

/**
 * HikariCP连接池配置
 */
@Configuration
public class DataSourceConfig {

    private static final Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);

    @Value("${spring.datasource.url}")
    private String dataSourceUrl;

    @Value("${spring.datasource.username}")
    private String user;

    @Value("${spring.datasource.password}")
    private String password;

    @Bean
    public DataSource primaryDataSource() {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(dataSourceUrl);
        config.setUsername(user);
        config.setPassword(password);
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");

        HikariDataSource ds = new HikariDataSource(config);
        return ds;
    }
}
/**
 * Tomcat 配置
 */
@Configuration
public class TomcatConfig {

    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        tomcat.setProtocol("org.apache.coyote.http11.Http11Nio2Protocol");//nio2 异步非阻塞
        return tomcat;
    }

}

 

@EnableAutoConfiguration

This annotation tells SpringBoot to "guess" how you will want to configure Spring, based on the jar dependencies you have added. If spring-boot-starter-web has added Tomcat and Spring MVC, this annotation will automatically assume you are developing a web application and add the corresponding spring settings.

In this way, @EnableAutoConfiguration can search for each annotated class from layer by layer. For example, if you are writing a JPA program (if you have configured it in your pom), spring will automatically search for classes annotated with @Entity. and make a call

 

@ComponentScan 

This annotation tells spring to automatically scan the java files under the base-pack or under the sub-package. If it scans classes with annotations such as @Component @Controller@Service, register these classes as beans.

 

@ConfigurationProperties

Used to inject parameters from the application configuration file into an entity class.
Usually we read through an input stream when we need to call configuration file parameters.
This method takes up system resources and is more troublesome.
E.g:

inputStream = ReadApplication.class.getClassLoader().getResourceAsStream(propertiesName);
properties.load(inputStream);
//或者
inputStream = new FileInputStream(file);
properties.load(inputStream);

Using the @ConfigurationProperties annotation can easily inject the content of the configuration file into an entity class for direct use

E.g:

configuration file

spring.datasource.url=jdbc:mysql://rdso30006c33s57oufvfo.mysql.rds.aliyuncs.com:3306/test?&zeroDateTimeBehavior=convertToNull
spring.datasource.username=test
spring.datasource.password=123654

entity class

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix="spring.datasource")
public class SpringDatasourceSettings {

    private String url;
    private String username;
    private String password ;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

inject and use

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class TestEndPoint {

    @Autowired
    SpringDatasourceSettings springDatasourceSettings;

    @RequestMapping(value = "v1.0/test", method = RequestMethod.POST)
    public String test( HttpServletRequest request) {
        System.out.println("openapi test : " + springDatasourceSettings.getUrl());
        System.out.println("openapi test : " + springDatasourceSettings.getUsername());
        System.out.println("openapi test : " + springDatasourceSettings.getPassword());

        return "";
    }
}

 

 

 

Guess you like

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