Spring Boot experience

1.Introduction to Spring Boot

1.1What is Spring Boot

Spring Boot is a Java-based open source framework used to simplify and accelerate the development process of Spring applications. It reduces developer workload by providing default and automated configuration, and provides a powerful set of tools and conventions that make it easier to build standalone, deployable Spring applications. Spring Boot provides a quick way to start a project and create a running Spring application in just a few simple steps. It integrates many commonly used Spring framework modules, such as Spring MVC, Spring Data, Spring Security, etc., allowing developers to focus more on the implementation of business logic without paying too much attention to underlying configuration and tedious code writing. Spring Boot also supports automated configuration, which automatically configures various components and functions of a Spring application based on the application's dependencies and settings. Developers can customize and override these default configurations to meet specific needs through simple configuration files or annotations.

1.2Features of Spring Boot

  1. Simplified configuration: Spring Boot reduces developer workload by providing default and automated configuration. It automatically configures various components and functions of Spring applications based on application dependencies and settings, eliminating the need for developers to manually write cumbersome configuration files.

  2. Quick Start: Spring Boot provides a way to quickly start a project and create a runnable Spring application in just a few simple steps. Developers can use Spring Initializr or command line tools to quickly generate project skeletons and integrate commonly used development tools and technology stacks.

  3. Embedded server: Spring Boot has a variety of commonly used servers built-in, such as Tomcat, Jetty, etc. Developers can directly run Spring applications without additional configuration and deployment of servers.

  4. Microservice support: Spring Boot provides a wealth of functions and tools to support the construction of microservice architecture. Developers can use Spring Cloud components, such as service registration and discovery, load balancing, circuit breakers, etc., to quickly build distributed systems.

  5. Monitoring and management: Spring Boot provides health checking, indicator collection, log management and other functions to facilitate developers to monitor and manage the running status of applications.

  6. Ecosystem: Spring Boot is built based on the Spring framework and can seamlessly integrate various Spring modules and third-party libraries. At the same time, Spring Boot also has an active community that provides a large number of plug-ins and extensions to facilitate developers to quickly integrate other technologies and tools.

1.3 Set up a development environment

Download, install and configure Maven, open the Maven official website and click Download

Select apache-maven-3.9.5-bin.zip

Maven does not need to be installed, just unzip it in the directory you need and edit the environment variables.

Open the unzipped directory and copy the directory path

Open the advanced settings of system information, click Environment Variables, and enter the Path of system variables.

Add the copied path to the variable

Check the installation status, click Start and enter the "cmd" command in the search box, then enter mvn - v. If the version information appears, the installation is successful.​ 

Configure Maven domestic warehouse

Enter the conf directory under the Maven installation directory, open the settings.xml file, find the <miror></mitor> tag to set the Alibaba Cloud mirror warehouse example, and add the following code.

2.Spring boot core configuration

  1. application.properties/application.yml: Spring Boot uses these configuration files to configure the properties of the application. You can specify database connection information, server ports, log levels, and more in these files.

  2. @Configuration annotation: Classes annotated with @Configuration are considered configuration classes, and Spring Boot will automatically load and apply the configuration at startup. You can define beans, configure data sources, set interceptors, etc. in the configuration class.

  3. @EnableAutoConfiguration annotation: Use the @EnableAutoConfiguration annotation to enable Spring Boot's automatic configuration. It automatically configures various components of the application based on the project's dependencies, such as data sources, message queues, Web MVC, etc. You can also exclude certain automatic configurations using @EnableAutoConfiguration(exclude = {...}).

  4. @ComponentScan annotation: Use the @ComponentScan annotation to specify the component scan path of the Spring Boot application and tell Spring Boot where to find Spring components.

  5. @Value annotation: Use the @Value annotation to inject attribute values ​​in the configuration file. You can use @Value("${property.name}") in Spring components to obtain property values, making it easier to use configured properties in code.

  6. External configuration files: In addition to application.properties/application.yml, Spring Boot also supports external configuration files. You can load a custom configuration file by specifying the --spring.config.name and --spring.config.location parameters.

To configure the port and context path for Web service access, the basic configuration is as follows

 Add a dependency in the pom.xml file - the configuration file processor, and you will be prompted when writing the configuration file. The code is as follows.

 3. Database operations

  1. Spring Data JPA: Spring Data JPA is a framework provided by Spring to simplify database access. It can automatically generate SQL statements by defining entity classes and interfaces, and provides a series of CRUD methods. To use Spring Data JPA, you need to add the corresponding dependencies in pom.xml and use annotations on the entity class for configuration. For specific usage, please refer to the official documentation of Spring Data JPA.

  2. MyBatis: MyBatis is an excellent persistence layer framework that can perform database operations through XML or annotations. To use MyBatis in Spring Boot, you need to add the corresponding dependencies and configure the data source and mapper scan path of MyBatis. At the same time, you need to write the Mapper interface and the corresponding SQL statement. For specific usage methods, please refer to the official documentation of MyBatis.

  3. JdbcTemplate: JdbcTemplate is a lightweight database access tool provided by Spring, which executes SQL statements by calling the methods it provides. To use JdbcTemplate, you need to add the corresponding dependencies in pom.xml and create a JdbcTemplate object in the code for database operations. You can use the methods provided by JdbcTemplate to perform add, delete, modify, and query operations. For specific usage, please refer to Spring's official documentation.

3.1 Link database

Database link

3.2 Task realization, role management of a company’s asset management system

Mission achievement

4.Spring Boot data cache management

4.1 Introduction to caching

 In SpringBoot development projects, Spring Boot transparently adds cache to the application, applies the cache to the method, and checks whether there is available data in the cache before the method is executed. This can reduce the number of method executions and increase the speed of response. The cache is enabled through the @EnableCaching annotation. After the cache is enabled, Spring Boot will automatically handle the basic configuration of the cache.
When a cache method is called, the parameters and return results of the method will be saved in the cache as key-value pairs. The next time the method is called with the same parameters, the method will not be executed. method, but directly obtains the results from the cache and returns them.
Therefore, when using SpringCache, ensure that the same result is returned when the cached method and method parameters are the same.

4.2 Cache annotations

In Spring Boot, you can use annotations to enable caching. There are mainly the following notes:

  1. @EnableCaching: Add this annotation to the startup class to enable caching.

  2. @Cacheable: Marked on a method, indicating that the return value of the method will be cached. When this method is called again, if the result already exists in the cache, the data in the cache will be returned directly and the method body will not be executed.

  3. @CachePut: Marked on a method, indicating that the return value of the method will be cached. Each time this method is called, the method body will be executed and the return value will be stored in the cache.

  4. @CacheEvict: Marked on the method, indicating that the method will remove the specified data from the cache.

  5. @Caching: You can use multiple cache annotations at the same time to combine cache operations.

In addition to the above annotations, Spring Boot also provides support for a variety of cache managers, including EhCache, Redis, Caffeine, etc. You can choose the cache manager that suits your application and configure it accordingly.

In terms of configuration, you can configure cache-related properties, such as cache name, expiration time, etc., in the application.properties or application.yml file. You can also configure the cache behavior in more detail by customizing the cache configuration class.

5.Spring Boot message queue

Spring Boot provides the function of integrating with the message queue, which can easily realize the sending and receiving of asynchronous messages. In Spring Boot, the most commonly used message queue implementations are using Apache Kafka and RabbitMQ.

  1. Apache Kafka: Kafka is a high-throughput, distributed publish-subscribe messaging system. By using Kafka, functions such as message persistence, reliable transmission, and horizontal expansion can be achieved. In Spring Boot, you can use the spring-kafka library to integrate Kafka, use KafkaTemplate to send messages, and use the @KafkaListener annotation to receive messages.

  2. RabbitMQ: RabbitMQ is an open source AMQP (Advanced Message Queuing Protocol) message queuing system. It supports multiple message transmission modes, including point-to-point, publish-subscribe, RPC, etc. In Spring Boot, you can use the spring-amqp library to integrate RabbitMQ, use RabbitTemplate to send messages, and use the @RabbitListener annotation to receive messages.

Using message queues can realize system decoupling, asynchronous processing, peak load shaving and valley filling, etc. It is suitable for scenarios that require decoupling and asynchronous processing, such as log processing, asynchronous notifications, task scheduling, etc.

In addition to Kafka and RabbitMQ, Spring Boot also supports the integration of other message queues, such as ActiveMQ, Redis message queue, etc. You can choose a suitable message queue implementation according to specific needs.

5.1 Message service

Spring Boot provides multiple ways to implement message services, the most common of which is to use Spring Integration and Spring Cloud Stream. Both methods can easily integrate message middleware and provide a unified programming model to send and receive messages.

  1. Spring Integration: Spring Integration is a lightweight integration framework that can seamlessly integrate various systems, applications and protocols. It provides a rich set of message processing components, such as channels, adapters, filters, converters, etc., which can easily send, receive and process messages. By integrating the message middleware adapter, Spring Integration can be integrated with message middleware (such as ActiveMQ, RabbitMQ) to realize message transmission and processing.

  2. Spring Cloud Stream: Spring Cloud Stream is a framework built on Spring Integration for building message-driven microservices. It provides a declarative way to define and bind message channels, decoupling the sending and receiving of messages from specific message middleware. Through Spring Cloud Stream, you can easily switch and integrate different message middleware, such as Kafka, RabbitMQ, etc.

5.2 Commonly used information middleware

  1. RabbitMQ: RabbitMQ is an open source message broker and queue server that supports multiple message protocols, such as AMQP, MQTT, etc. Spring Boot provides automatic configuration and integration support for RabbitMQ.

  2. Apache Kafka: Kafka is a distributed stream processing platform with high throughput, scalability and durability. Spring Boot provides automatic configuration and integration support for Kafka.

  3. ActiveMQ: ActiveMQ is an open source message middleware that supports the JMS (Java Message Service) specification. Spring Boot provides automatic configuration and integration support for ActiveMQ.

  4. Redis: Redis is an in-memory data storage system that can also be used as message middleware. Spring Boot provides automatic configuration and integration support for Redis, and you can use Redis as a message queue.

  5. Apache Pulsar: Pulsar is an open source distributed messaging and streaming platform with high performance, multi-tenancy and scalability. Spring Boot can use Pulsar as message middleware by integrating the Pulsar client library.

6.Spring Boot security mechanism

  1. Role-based access control: Spring Security is the core security framework of Spring Boot, which can implement role-based access control. By configuring roles and permissions, you can restrict user access to application resources.

  2. Form authentication: Spring Security provides a form-based authentication mechanism. Users can enter their username and password for authentication through the login page. The login page and authentication logic can be customized, and third-party authentication services can be integrated.

  3. OAuth 2.0: Spring Security also supports the OAuth 2.0 protocol, which can implement token-based authentication and authorization. You can use the Spring Security OAuth module to integrate OAuth 2.0 functionality.

  4. JWT (JSON Web Token): JWT is a JSON-based security token. Spring Security can use JWT to implement stateless authentication and authorization. JWT can contain data such as user information and permissions, which can reduce the burden on the server for identity authentication.

  5. HTTPS: Spring Boot provides the ability to configure HTTPS, which can achieve secure transmission by configuring an SSL certificate. You can use the built-in Tomcat or Jetty server, or use an external reverse proxy server to implement HTTPS.

  6. Security events and logs: Spring Security provides security event and logging functions, which can record various security-related events, such as successful login, access denial, etc. These events can be monitored and processed and recorded accordingly.

6.1What is JWT

  1. Header: The header usually consists of two parts, the type of token (i.e. JWT) and the signature algorithm used (such as HMAC SHA256 or RSA, etc.).

  2. Payload: The payload is the main content of JWT and contains some claims (Claims) used to describe token-related information. It can contain additional data such as user identity information, permissions, etc.

  3. Signature: A signature is the result of signing the header and payload to ensure the integrity and authenticity of the token. Signatures are usually generated using a key, and only the person holding the key can verify the validity of the signature.

The advantages of JWT are simplicity, self-containment and extensibility. Since JWT uses JSON format to store information, it can be easily transferred between different platforms and languages. JWT can also extend its functionality by adding custom claims and supports adding additional metadata to the token.

When using JWT, the server generates a JWT and sends it to the client, who then passes the token by including it in the header of the request or elsewhere. The server can verify the validity of the token and authorize and process the request based on the information in the token.

JWT is often used for authentication and authorization, especially for distributed systems and applications with front-end and back-end separation. By using JWT, a reliable authentication and authorization mechanism can be implemented without relying on session state.

6.2JWT authentication process

  1. User login: The user provides username and password for login verification.

  2. Server verification: The server verifies whether the username and password provided by the user are correct, and if the verification passes, a JWT is generated.

  3. JWT generation: The server uses the private key to sign the JWT header and payload, and generates a signed JWT.

  4. JWT return: The server returns the generated JWT to the client, usually as part of the response, which can be placed in the HTTP response header, response body, or cookie.

  5. Client-side storage: After the client receives the JWT, it usually stores it locally, such as in the browser's localStorage or cookie.

  6. Request sending: In subsequent requests, the client uses JWT as an authentication credential and places it in the request header, request parameters or request body.

  7. Server verification: After the server receives the request, it extracts the JWT from the request and uses the public key to verify whether the JWT's signature is valid and complete.

  8. Identity authentication: The server determines the user's identity and permissions based on the payload information in the JWT. If the verification passes, the request is processed; otherwise, the corresponding error message is returned.

One of the advantages of JWT is that it is stateless, so the server does not need to store the user's state information in itself and can verify the validity of the user by verifying the signature of the JWT. This design makes JWT very suitable for use in distributed systems and microservice architectures, while also reducing the burden on the server.

7. Experience after learning Spring Boot

7.1 Self-experience

Learning Spring Boot is a big gain in my programming learning process. As a beginner, I found that Spring Boot has a relatively low learning curve and is relatively easy to get started. It provides automatic configuration and the principle of convention over configuration, allowing developers to quickly build and deploy applications without paying too much attention to tedious configuration details.

In the process of learning Spring Boot, I found that its documentation and tutorials are very rich, which allowed me to quickly understand and master its core concepts and usage. At the same time, the Spring Boot community is also very active, where developers can communicate and share experiences and receive timely help and feedback.

Spring Boot provides a wealth of functions and components to meet the needs of different application scenarios. It integrates database operation frameworks such as Spring Data JPA and MyBatis, making database operations easier. At the same time, it also provides support for functions such as caching, message queues, and security authentication, allowing developers to quickly integrate these functions into applications.

In actual application development, I deeply realized the advantages of Spring Boot. Its modular design and loosely coupled architecture make applications easier to expand and maintain. At the same time, Spring Boot provides powerful testing support, making it easy to write unit tests and integration tests to ensure the quality and stability of applications.

In addition, the Spring Boot ecosystem is also very powerful, and there are many excellent open source projects and frameworks that can be integrated with it. For example, Spring Cloud provides a wealth of microservice components to easily build and manage distributed systems. The existence of these projects provides us with more choices and flexibility.

Overall, learning Spring Boot gave me a new understanding of Java application development. Its simplicity and powerful features make the development process more efficient and enjoyable. I believe that Spring Boot will be one of my preferred frameworks in future development work.

 7.2 Thoughts on code

Learning and using Spring Boot has brought me a lot of gains and experiences. First of all, Spring Boot greatly simplifies the development process of Java applications, reducing tedious configuration and repeated code. Through automatic configuration and the principle of convention over configuration, we can quickly build a basic application framework, eliminating a lot of complicated work. This allows me to focus more on the implementation of business logic and improves development efficiency.

Secondly, Spring Boot integrates rich functions and components, such as database operation framework, cache and message queue. The integration of these functions makes it more convenient for me to use these tools during the development process, without the need to manually configure and introduce third-party libraries. For example, using Spring Data JPA can simplify the writing of database operations and reduce the amount of writing SQL statements. Using Spring Cache can easily implement the caching function and improve the performance of the system. The integration of these functions allows me to focus more on the implementation of business logic without spending too much energy on the underlying technical details.

In addition, Spring Boot has a good ecosystem and community support. In the process of learning and using Spring Boot, I found that there are many excellent open source projects and documentation resources for reference. By consulting documentation and participating in community discussions, I was able to quickly solve problems I encountered and learned many other developers’ experiences and techniques. This huge community has given me many opportunities to learn and grow.

Overall, learning Spring Boot gave me a new understanding of Java application development. Its simplicity, efficiency and rich functions bring me a lot of convenience and happiness. By learning and using Spring Boot, I have improved my development efficiency and deepened my understanding of the Java technology stack. I believe that Spring Boot will become one of my indispensable development tools in my future work.

Guess you like

Origin blog.csdn.net/2301_78093624/article/details/134238929