What is Springboot?

Springboot scaffolding simplifies configuration and dependency management features: quick setup, embedded application server, automatic configuration, no code generation, and no XML configurationCopy the code

An introduction to case

1. Import the parent dependency and specify SpringBoot version 2.1.5

2. Add an initiator class

3. Write boot classes

4. Write the processor

pom.xml

Manage maven dependencies <? 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> Dependencies for springboot management <parent> <groupId>org.springframework.boot</groupId> < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.1.5. RELEASE < / version > < / parent > < groupId > cn, LXG < / groupId > <artifactId>springboot_luoxg_day01_01</artifactId> <version>1.0-SNAPSHOT</version> JDK version <properties> <java.version>1.8</java.version> </properties> SpringBoot dependencies <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>Copy the code

The controller to control the class

package cn.lxg.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @restController Public Class HelloController {@getMapping ("hello")
    public String helloSpringBoot() {
        return "Hello SpringBoot!"; }}Copy the code

Application to guide class

package cn.lxg; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import javax.swing.*; Public static void main(String[] args) {public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Copy the code

The first option is to configure a DataSource

1. Create the jdbc.properties configuration file

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/account
jdbc.username=root
jdbc.password=lncnetwork
Copy the code

2. Create a jdbcConfig configuration class

package cn.lxg.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import javax.sql.DataSource; @configuration // The table name is currently a Configuration class @propertysource ("classpath:jdbc.properties"Public class JdbcConfig {//Value adds data to the config file @value ("${jdbc.driverClassName}")
    private String driverClassName;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

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

    @Bean("dataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(this.driverClass);
        dataSource.setUrl(this.url);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);
        returndataSource; }}Copy the code

3. Directly invoke the data source

package cn.lxg.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.sql.DataSource; import java.sql.Connection; The result is the string @restController Public Class HelloController {@resource (name =)"dataSource")
    private DataSource dataSource;

    @GetMapping("hello")
    public String helloSpringBoot() {
        System.out.println(dataSource);
        return "Hello SpringBoot!"; }}Copy the code

Configure a DataSource DataSource

1. Create the application. The properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/account
jdbc.username=root
jdbc.password=lncnetwork
Copy the code

2. Use the ConfigurationProperties annotation to inject data

package cn.lxg.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:application.properties")
public class JdbcConfig {

    @Bean("dataSource")
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        returndataSource; }}Copy the code

Third: YML file configuration

Common data configuration
name: zhangsan
Object configuration
person:
  name: zhangsan
  age: 18
  addr: beijing

Inline object configuration
person1: {name: zhangsan,age: 18,addr: beijing}

Configure data, set
city:
  - beijing
  - tianjing
  - chognqing

# Inline configuration data, collection
city1: [beijing,tianjing,chongqing]

Configure data, set (object data)
student:
  - name: tom
    age: 18
    addr: beijing
  - name: lucy
    age: 17
    addr: tianjing

Inline configuration data, collection (object data)
student1: [{name: tom,age: 17,adrr: tianjing},{name: tom1,age: 16,adrr: tianjing}]

# map configuration
map:
  key1: value1
  key2: value2
Copy the code

Obtain the YML file

1. Get the Value via the @value annotation

  @Value("${name}")
    private String name;
Copy the code

Note @configurationProperties

configuration

person:
  name: zhangsan
  age: 18
  addr: beijing
Copy the code

Class method

@Controller
@ConfigurationProperties(prefix = "person")
public class Quick3Controller {

    private String name;
    private String addr;

    @RequestMapping("/quick3")
    @ResponseBody
    public String quick2() {return name + "" + addr;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) { this.addr = addr; }}Copy the code

Example yML configuration file

application.yml

jdbc: driverClassName: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/account username: root password: Lncnetwork Spring: Profiles: active: A, B // Activate YML profiles of A and BCopy the code

application-a.yml

luoxg:
  name: luoxg
Copy the code

application-b.yml

lncnetwork:
  name: nb
Copy the code

HelloController

@RestController
//@PropertySource("classpath:application.yml"Public class HelloController {@resource (name =)"dataSource")
    private DataSource dataSource;

    @Value("${luoxg.name}")
    private String luoxg;

    @Value("${lncnetwork.name}")
    private String lncnetwork;
    
}
Copy the code

Modifying tomcat Ports

server:
	port: 80
Copy the code

Spring Boot Directory for storing static resources

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
			"classpath:/META-INF/resources/"."classpath:/resources/"."classpath:/static/"."classpath:/public/" };
Copy the code

The interceptor

1. Create your own MyInterceptor class to implement HandlerInterceptor

package cn.lxg.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("MyInterceptor -- preHandle executed");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.debug("MyInterceptor -- postHandle executed");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.debug("MyInterceptor -- afterCompletion executes"); }}Copy the code

2. Write a configuration class to implement WebMvcConfigurer

package cn.lxg.config; import cn.lxg.interceptor.MyInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @configuration public class MvcConfig implements WebMvcConfigurer {// @bean public MyInterceptormyInterceptor() {
        return new MyInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor()).addPathPatterns("/ *"); }}Copy the code

Transaction management

1. Add transaction related initiator dependencies, mysql related dependencies

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
Copy the code

2. Configure hiKARi for the database connection pool

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/account
    username: root
    password: lncnetwork
Copy the code

3. Write pseudo access data classes

Transactional: Enables transaction support

package cn.lxg.service;

import cn.lxg.domain.Account;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountService {

    public void save(Account acc) {
        System.out.println("Save account information"); } @transactional // enable Transactional support public Account selOne(int id) {returnnew Account(); }}Copy the code

Mybatis SpringBoot integration

1. Add initiator dependencies

<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> The < version > 2.1.1 < / version > < / dependency >Copy the code

2. Configure MyBatis: entity category name package, log, mapping file, etc.

mybatis:
  # entity class name path
  type-aliases-package: cn.lxg.pojo
  # map file address
  mapper-locations: classpath:mapper/*.xml
  # config log
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Copy the code

3. The configuration MapperScan

package cn.lxg; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import javax.swing.*; @springBootApplication // Scan mybatis all business Mapper interface @mapperscan ("cn.lxg.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Copy the code

##SpringBoot integrate universal Mapper through Mapper: can implement since all give you splice SQL statements; All mapper’s don’t need to write any methods that are just SQL statements. Can improve development efficiency

1. Add initiator dependencies

<! Mapper--> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> The < version > 2.1.5 < / version > < / dependency >Copy the code

2. Transform AccountMapper to inherit Mapper

package cn.lxg.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {

    private Integer id;
    private String name;
    private Float money;

}

Copy the code

3. Modify the Mapper scan annotation in the bootstrap class Application

package cn.lxg; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import tk.mybatis.spring.annotation.MapperScan; @springBootApplication // Scan mybatis all business Mapper interface @mapperscan ("cn.lxg.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Copy the code

4. Modify the Account entity class to add JAP annotations

package cn.lxg.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import tk.mybatis.mapper.annotation.KeySql;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "account") public class Account {@id // Primary key backfill @keysQL (useGeneratedKeys =true)
    private Integer id;

    @Column(name = "name"// Support hump private String name; @Column(name ="money")
    private Float money;

}
Copy the code

5. Modify the AccountService to implement service functions

package cn.lxg.service; import cn.lxg.domain.Account; import cn.lxg.mapper.AccountMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @service public class AccountService {@autoWired // Automatic assembly private AccountMapper AccountMapper; public void saveAccount(Account acc) { accountMapper.insertSelective(acc); } @Transactional public Account findById(int id) { Account account = accountMapper.selectByPrimaryKey(id);returnaccount; }}Copy the code

Test 6.

package cn.lxg.controller; @restController Public Class HelloController {@AutoWired Private AccountService AccountService; @RequestMapping("findById/{id}")
    public Account findById(@PathVariable Integer id) {
        returnaccountService.findById(id); }}Copy the code

SpringBoot integrated Junit

To write a test class in SpringBoot, you must add @SpringBooTtest to the class

1. Add the junit initiator

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
Copy the code

2. Write test classes

package cn.lxg.service;

import cn.lxg.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AccountServiceTest {

    @Autowired
    private AccountService accountService;

    @Test
    public void saveAccount() {
        Account account = new Account();
        account.setName("Roshuby");
        account.setMoney(99999F);
        System.out.println(account);
        accountService.saveAccount(account);
        System.out.println(account);
    }

    @Test
    public void findById() { Account byId = accountService.findById(20); System.out.println(byId); }}Copy the code

SpringBoot integrate Redis

1. Add an initiator dependency. spring-boot-starter-data-redis

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

Copy the code

2. Modify redis connection parameters in applciation.yml. (Redis needs to be started)

  redis:
    host: localhost
    port: 6379

Copy the code

3. Write test classes and apply RedisTemplate to manipulate data in 5 of Redis

package cn.lxg.redis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import javax.sound.midi.Soundbank;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRedis {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testRedis1() {/ / string redisTemplate. BoundValueOps ("name").set("Zhang");
        System.out.println(redisTemplate.opsForValue().get("name"));
//        hashHash redisTemplate. BoundHashOps ("h_key").put("name"."luoxg"); / / get the key redisTemplate. BoundHashOps ("h_key").keys(); / / get the value redisTemplate. BoundHashOps ("h_key").values();
        System.out.println(redisTemplate.boundHashOps("h_key").get("name")); / / the list list redisTemplate. BoundListOps ("names").leftPush("l");
        redisTemplate.boundListOps("names").leftPush("x");
        redisTemplate.boundListOps("names").leftPush("g"); / / get the list value System. Out.println (redisTemplate. BoundListOps ("names").range(0,-1));
//        setCollection redisTemplate. BoundSetOps ("ages").add("1"."23"."19");
        System.out.println(redisTemplate.boundSetOps("ages").members());
//        sorted setAn ordered set redisTemplate. BoundZSetOps ("z_key").add("a", 30); redisTemplate.boundZSetOps("z_key").add("b", 20); redisTemplate.boundZSetOps("z_key").add("c", 10); System.out.println(redisTemplate.boundZSetOps("z_key").range(0,-1)); }}Copy the code

SpringBoot project deployment

1. You need to add a package component to put the resource, configuration, and dependency packages in the project into a JAR package; Maven’s package can be used

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

2. Deployment: Java-jar package name

Java jar springboot_luoxg_day01_01-1.0 - the SNAPSHOT. The jarCopy the code

Principle of Automatic configuration

1. All auto-configuration classes are defined in the Spring. factories file. Eliminate initiator dependency instantiation

2. Configuration process

Spring-boot-autoconfigure -***.jar 2 Find the package of the current component in the jar above. 3. Look at the **Properties configuration item class 4. Go to the Application. yml configuration file in Spring Boot to modify the configuration itemsCopy the code

The last

Thank you for watching. If you don’t understand anything, please ask me in the comments section. If you think this article is helpful to you, please give me a thumbs up.