SpringBoot entry Daquan summary

Welcome to my personal blog: www.ifueen.com

Outline

springBoot is a sub-project of the Spring project, and we know Spring-framework belong to the spring of the product, use springboot, allow us to build a huge spring projects (including web persistent) quickly, and reduce all possible xml configuration, so out of the box, quickly get started, let's focus on business rather than configuration

Why use SpringBoot?

It appears to solve the traditional spring project the following questions:

  • Configuration is responsible for many

Each component corresponds to an integrated spring will need to write the configuration file, such as appplicationContext-xxx.xml

  • Confusion dependency management

When spirng want to integrate the corresponding component, the need to import more N pom, and there regardless of the version.

We use SpringBoot create java applications, simply fill out the little configuration and dependency will be able to quickly set up and use java -jar start it, you can get a production-level web project. Very convenient

getting Started

First created a maven project and then rely in pom.xml

<!-- 指定SpringBoot的版本 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>

    <!-- 导入SpringBoot的Jar包-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

Then write a Controller class

package com.ifueen.hello;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "Hello SpringBoot";
    }
}

Finally, write a configuration class to start

package com.ifueen.hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * SpingBoot的引导类
 */
@SpringBootApplication
public class HelloSpringBoot {
    public static void main(String[] args){
        //加载这个控制器
        SpringApplication.run(HelloSpringBoot.class);
    }
}

This configuration classes start, and then enter localhost in the browser: 8080 / hello you can see the effect

Project structure

The basic structure of the project follows a SpingBoot

src
	--main
		--java
		--resources
			--static		//静态资源目录
			--templates		//模板页面目录,如:jsp ,ftl
			--application.properties/application.yml	//默认配置文件

Bale

introducing pom.xml packaged plug

<build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

After completion packaged in cmd run command

java -jar xxx.jar

SpringBoot reads the configuration

Use @Value label

Profiles

# 设置端口
server.port=5050

Bound object configuration

//读取端口
    @Value("${server.port}")
    private String port;

Use @ConfigurationProperties

Profiles

#配置数据库
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql:///rpms?useUnicode=true&characterEncoding=utf-8
db.username=root
db.password=123456

Create a class to store the configuration read

package com.ifueen.hello.read_properties;

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

/**
 * 读取配置文件的类
 */

@Component
@ConfigurationProperties(prefix = "db")
public class DbProperties {

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

    @Override
    public String toString() {
        return "DbProperties{" +
                "driverClassName='" + driverClassName + '\'' +
                ", url='" + url + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    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;
    }
}


Multi-switch environment

method one

spring:
  profiles:
    active: test	#激活(选择)环境test
---
spring:
  profiles: dev		#指定环境名字dev
server:
  port: 9999
---
spring:
  profiles: test	#指定环境名字test
server:
  port: 8888

Second way

To identify the name of the configuration file by environment

application-dev.yml

server:
  port: 9999

application-test.yml

server:
  port: 8888


application.yml

spring:
  profiles:
    active: test 
    #根据文件名字配置 application-dev.properties


Use the log

Basic use

//日志
    private static Logger log = LoggerFactory.getLogger(HelloController.class);
		
		log.debug(connection.toString());
        log.error("错误信息s");
        log.warn("警告信息");
        log.info("详细信息");


Configuring Log

# 配置日志
logging.level.root=info
logging.level.com.ifueen.hello=trace
logging.file=mylog.log
logging.pattern.console=%white(%d{yyyy-MM-dd HH:mm:ss}) %highlight(%lsn) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{10}) - %cyan(%msg%n)
logging.pattern.file=%white(%d{yyyy-MM-dd HH:mm:ss}) %highlight(%lsn) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{10}) - %cyan(%msg%n)


Specifies the profile configuration logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration  scan="true" scanPeriod="5 seconds" debug="false">

    <!-- 定义输出日志的格式和位置 -->
    <property name="SpringBoot_Log" value="%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n" />


    <!--输出到控制台-->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${SpringBoot_Log}</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <!--输出到文件-->
    <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logs/springboot.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>logs/springboot-%d{yyyyMMdd}-%i.log.gz</fileNamePattern>
            <!-- 单个文件最大值 -->
            <maxFileSize>5KB</maxFileSize>
            <!-- 保留历史 -->
            <maxHistory>30</maxHistory>
            <!-- 总文件大小 -->
            <totalSizeCap>1GB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <pattern>${SpringBoot_Log}</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>
    <!-- 输出级别 -->
    <root level="info">
        <appender-ref ref="console" />
        <appender-ref ref="file" />
    </root>


    <logger name="com.ifueen" level="trace" additivity="false">
        <appender-ref ref="console"/>
        <appender-ref ref="file"/>
    </logger>
</configuration>



SpringBoot integrated Thymeleaf

Import dependence

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


Create a template resources / templates / hello.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>欢迎奥</title>
    <script src="webjars/jquery/3.4.1/jquery.js"></script>
</head>
<script>
    alert($)
</script>
<body>
    <h1>让我康康</h1>
    <div th:text="${msg}"></div>
</body>
</html>


Controller Configuration

@RequestMapping("/hello")
    public String home(Model model){
        model.addAttribute("msg","我们不能失去信仰");
        return "hello";
    }


Automatic configuration of principle Thymeleaf

@EnableAutoConfiguration 开启自动配置功能,通过一个AutoConfigurationImportSelector导入选择器去扫描 spring-boot-autoconfigure-2.0.5.RELEASE.jar 自动配置包下面的 spring.factories 文件中的很多很多的自动配置的类
而:ThymeleafAutoConfiguration 是的Thymeleaf的自动配置 ,在这个自动配置类里面通过一个ThymeleafProperties去读取配置文件中的配置(也有默认配置) ,来自动配置Thymeleaf,比如Thymeleaf的视图解析器的自动配置如下:



@Bean
@ConditionalOnMissingBean(name = "thymeleafViewResolver")
public ThymeleafViewResolver thymeleafViewResolver() {
	ThymeleafViewResolver resolver = new ThymeleafViewResolver();
	...
	return resolver;
}


Static resources

1. Static Resource Directory

resource/static

2.webjars

Introducing jquery dependent (http://www.webjars.org/)

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.4.1</version>
</dependency>


Import of js jquery

<script src="/webjars/jquery/3.4.1/jquery.js"></script>


MVC configuration of SpringBoot

1. Configure interceptor

Defines interception

package com.ifueen.hello;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 */
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截");
        return true;
    }
}



Registration interceptor

package com.ifueen.hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * SpringMVC的配置
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Autowired
    private LoginCheckInterceptor loginCheckInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //拦截所有
        registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/xx").setViewName("xx.html");
    }

}



2. Add the view controller
 @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/xx").setViewName("hello2.html");
    }


When accessing / xx targeting templates / hello2.html

Integrated the DataSource (connection pool)

1. Import dependence
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.20</version>
        </dependency>
        <!-- mysql 数据库驱动. -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>


Manual configuration

Manually configure four properties

db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql:///rpms?useUnicode=true&characterEncoding=utf-8
db.username=root
db.password=123456


    @Bean
    @ConfigurationProperties(prefix = "db")
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        return dataSource ;
    }


Automatic configuration (Key)

# 配置datasource -- 自动配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql:///rpms?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456


Published 87 original articles · won praise 7 · views 20000 +

Guess you like

Origin blog.csdn.net/f2315895270/article/details/103240953