Spring-boot in-depth analysis

SpringBoot

What is Spring Boot?

Spring Boot is designed to simplify the initial construction and development process of new Spring applications, to allow developers to create and allow Spring applications as quickly as possible, and to reduce project configuration files as much as possible.

At its most fundamental, Spring Boot is a collection of libraries that can be used by any project's build system. It uses the concept of "habit over configuration" (there are a lot of configurations in the project, plus a built-in configuration for habits) to get your project up and running quickly. So spring boot is not actually a new framework. It is configured with many frameworks by default, just like maven integrates all jar packages, and spring boot integrates all frameworks.

To sum it up:

(1) Provide a faster and broader entry experience for all Spring development.

(2) Zero configuration. No redundant code generation and XML mandatory configuration, following "convention over configuration".

(3) Integrate the configuration of a large number of commonly used third-party libraries. Spring Boot applications provide these third-party libraries with almost zero-configuration out-of-the-box capabilities.

(4) Provides a series of non-functional features commonly used in large projects, such as embedded servers, security, metrics, health checks, externalized configuration, etc.

(5) Spring Boot is not a substitute for Spring, the Spring framework manages Beans through the IOC mechanism. Spring Boot relies on the Spring Framework to manage object dependencies. Spring Boot is not a stripped-down version of Spring, but a variety of production-level preparations for using Spring.

SpringBoot core functions

1. Run the Spring project independently
Spring boot can run independently in the form of a jar package. To run a Spring Boot project, you only need to run it through java -jar xx.jar.
2. The embedded servlet container
Spring Boot can choose to embed Tomcat, jetty or Undertow, so that we do not need to deploy the project in the form of war package.
3. Provide starter to simplify Maven configuration
Spring provides a series of start poms to simplify Maven dependency loading. For example, when you use spring-boot-starter-web, dependency packages will be added automatically.
4. Automatic assembly Spring
SpringBoot will automatically configure beans for the classes in the jar package according to the jar package, class, and class in the jar package, which will greatly reduce the configuration we want to use. Of course, SpringBoot only considers most development scenarios, not all scenarios. If we need to configure beans in actual development, and SpringBoot provides support, you can customize automatic configuration.
5. Quasi-production application monitoring
SpringBoot provides monitoring of runtime projects based on http ssh telnet.
6. No-code production and xml configuration

SpringBoot is not implemented by means of code generation, but by conditional annotation, which is a new feature provided by Spring4.x.

SpringBoot advantages and disadvantages

advantage:

1. Quickly build the project.
2. Configuration-free integration of mainstream development frameworks.
3. The project can run independently without external dependencies on the Servlet container.
4. Provide application monitoring at runtime.
5. Greatly improve the development and deployment efficiency.
6. Natural integration with cloud computing.

shortcoming:

1. If you don't agree with the spring framework, maybe this is a disadvantage.
2. SpringBoot features
3. Create independent Spring projects
4. Built-in Tomcat and Jetty containers
5. Provide a starter POMs to simplify Maven configuration
6. Provide a series of non-functional features common in large projects, such as security, metrics, health Detection, external configuration, etc.
7. No code generation and xml configuration files at all

Several commonly used annotations of SpringBoot

(1) @RestController and @Controller specify a class as an annotation for the controller, and explain the difference
(2) @RequestMapping method-level mapping annotation, this one who has used Spring MVC is believed to be familiar
(3) @ EnableAutoConfiguration and @SpringBootApplication are class-level annotations, which automatically guess the correct spring configuration according to the jar that maven depends on. As long as the dependency of spring-boot-starter-web is introduced, Spring MVC and tomcat containers will be automatically configured by default
(4 ) @Configuration class-level annotation. Generally, this annotation is used to identify the class where the main method is located and complete the initialization of the metadata bean.
(5) @ComponentScan class-level annotation, which automatically scans and loads all Spring components including bean injection, generally used on the class where the main method is located
(6) @ImportResource class-level annotation, when we must use an xml configuration, use @ImportResource and @Configuration to identify the class of this file resource.
(7) @Autowired annotation, generally combined with @ComponentScan annotation, to automatically inject a Service or Dao-level Bean
(8) @Component class-level annotation, used to identify a component, for example, if I customize a filter, this annotation is required After the identification, Spring Boot will recognize it correctly.

1. Parse the pom.xml file:

(1) Let's take a look at what is in the default generated pom.xml 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>com.xpwi</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

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

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


</project>

(2) We can see a relatively unfamiliar label, which is configuring the parent dependency of Spring Boot:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
 </parent>

With this, the current project is the Spring Boot project, and spring-boot-starter-parent is a special starter, which is used to provide related Maven default dependencies. After using it, the version tag can be omitted for commonly used package dependencies. .

2 Mapping with annotation @ConfigurationProperties

By annotating **@ConfigurationProperties(prefix=“the prefix of the key in the configuration file”)**, the configuration in the configuration file can be automatically mapped to the entity

application.properties is configured as follows:

person:
  name: zhangsan
  age: 18
或者,application.yml配置如下:
person:
  name: zhangsan
  age: 18

The entity bean code is as follows:

@Controller
@ConfigurationProperties(prefix = "person")
public class QuickStartController {
    
    
            private String name;
            private Integer age;

@RequestMapping("/quick")
@ResponseBody
public String quick(){
    
    
    return "springboot 访问成功! name="+name+",age="+age;
}

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

public void setAge(Integer age) {
    
    
    this.age = age;
}

Note: The automatic mapping between configuration files and entity fields can be performed using the @ConfigurationProperties method, but the fields must provide set methods, and fields modified with @Value annotations do not need to provide set methods

8. SpringBoot integrates with other technologies

1 SpringBoot integrates Mybatis

1. Add the starting dependencies of Mybatis

<!--mybatis起步依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>

2. Add database driven coordinates

<!-- MySQL连接驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

3 Add database connection information

Add connection information for the amount of data in application.properties

Note: The higher version of the url now needs to set the time zone and other information

#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTCuseUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456

4 Create the user table

Create the user table in the test database


-- Table structure for `user`-- ----------------------------DROP TABLE IF EXISTS `user`;CREATE TABLE `user` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `username` varchar(50) DEFAULT NULL,  `password` varchar(50) DEFAULT NULL,  `name` varchar(50) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;-- ------------------------------ Records of user-- ----------------------------INSERT INTO `user` VALUES ('1', 'zhangsan', '123', '张三');INSERT INTO `user` VALUES ('2', 'lisi', '123', '李四');

5. Create entity beans

public class User {
    
        // 主键    private Long id;    // 用户名    private String username;    // 密码    private String password;    // 姓名    private String name;
//此处省略getter和setter方法 .. ..

6 Write Mapper

@Mapperpublic interface UserMapper {	public List<User> queryUserList();}

Note: @Mapper marks this class as a mapper interface of mybatis, which can be automatically scanned into the spring context by spring boot

7. Configure Mapper mapping file

Add the UserMapper.xml configuration file to the src\main\resources\mapper path"

<?xml version="1.0" encoding="utf-8" ?>
select * from user

8. Add mybatis information in application.properties

#spring集成Mybatis环境#pojo别名扫描包mybatis.type-aliases-package=com.itheima.domain#加载Mybatis映射文件mybatis.mapper-locations=classpath:mapper/*Mapper.xml

9, write a test Controller

@Controllerpublic class MapperController {@Autowiredprivate UserMapper userMapper;@RequestMapping("/queryUser")@ResponseBodypublic List<User> queryUser(){    List<User> users = userMapper.queryUserList();    return users;}

10 tests

3. SpringBoot integrates Junit

1 Add Junit's starting dependencies

<!--测试的起步依赖--><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-test</artifactId>    <scope>test</scope></dependency>

2 Write the test class

package com.itheima.test;import com.itheima.MySpringBootApplication;import com.itheima.domain.User;import com.itheima.mapper.UserMapper;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 java.util.List;@RunWith(SpringRunner.class)@SpringBootTest(classes = MySpringBootApplication.class)public class MapperTest {
    
    @Autowiredprivate UserMapper userMapper;@Testpublic void test() {
    
        List<User> users = userMapper.queryUserList();    System.out.println(users);}

Among them, SpringRunner inherits from SpringJUnit4ClassRunner, whichever test engine provided by Spring can be used

public final class SpringRunner extends SpringJUnit4ClassRunner

The attribute of @SpringBootTest specifies the bytecode object of the boot class

3 console print information

1.SpringBoot整合Spring Data JPA

3.1 Add the starter dependencies of Spring Data JPA

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

3.2 Add database driver dependencies

<dependency>    <groupId>mysql</groupId>    <artifactId>mysql-connector-java</artifactId></dependency>

3.3 Configure database and jpa related properties in application.properties

#DB Configuration:spring.datasource.driverClassName=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8spring.datasource.username=rootspring.datasource.password=123456#JPA Configuration:spring.jpa.database=MySQLspring.jpa.show-sql=truespring.jpa.generate-ddl=truespring.jpa.hibernate.ddl-auto=updatespring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy

3.4 Create entity configuration entity

@Entitypublic class User {    // 主键    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Long id;    // 用户名    private String username;    // 密码    private String password;    // 姓名    private String name;
//此处省略setter和getter方法... ...

3.5 Writing UserRepository

public interface UserRepository extends JpaRepository<User,Long>{ public List findAll();

}

3.6 Writing test classes

@RunWith(SpringRunner.class)
@SpringBootTest(classes=MySpringBootApplication.class)
public class JpaTest {

@Autowiredprivate UserRepository userRepository;@Testpublic void test(){    List<User> users = userRepository.findAll();    System.out.println(users);}

3.7 Console Printing Information

Note: If it is jdk9, the execution error is as follows:

Reason: jdk is missing the corresponding jar

Solution: Manually import the corresponding maven coordinates, as follows:

<!--jdk9需要导入如下坐标--><dependency>    <groupId>javax.xml.bind</groupId>    <artifactId>jaxb-api</artifactId>    <version>2.3.0</version></dependency>

jdk8 is normal

4. SpringBoot integrates Redis

1 Add the starting dependencies of redis

<!-- 配置使用redis启动器 --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-redis</artifactId></dependency>

2 Configure the connection information of redis

#Redisspring.redis.host=127.0.0.1spring.redis.port=6379

3 Inject RedisTemplate to test redis operations

@RunWith(SpringRunner.class)@SpringBootTest(classes = SpringbootJpaApplication.class)public class RedisTest {
    
    @Autowiredprivate UserRepository userRepository;@Autowiredprivate RedisTemplate<String, String> redisTemplate;@Testpublic void test() throws JsonProcessingException {
    
        //从redis缓存中获得指定的数据    String userListData = redisTemplate.boundValueOps("user.findAll").get();    //如果redis中没有数据的话    if(null==userListData){        //查询数据库获得数据        List<User> all = userRepository.findAll();        //转换成json格式字符串        ObjectMapper om = new ObjectMapper();        userListData = om.writeValueAsString(all);        //将数据存储到redis中,下次在查询直接从redis中获得数据,不用在查询数据库        redisTemplate.boundValueOps("user.findAll").set(userListData);        System.out.println("===============从数据库获得数据===============");    }else{        System.out.println("===============从redis缓存中获得数据===============");    }    System.out.println(userListData);}

Guess you like

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