One of the reading notes of "In-depth Practice of Spring Boot": Basic Application Development

 

For the application of follow-up projects, I want to use these two days to read "In-depth Practice of Spring Boot". This book was bought on JD.com during the Double Eleven in 2017, and I haven't read it. This book is more practical and suitable for beginners to read. The text content is only more than 240 pages, so it will be easier to read.

At present, I have finished reading the first part, which accounts for about 1/2 of the whole book. I plan to read this book before going to work on the seventh day of the new year. I will introduce it in 3 articles. This article first introduces the overall structure of the book, and then summarizes the content of the first part.

I won't introduce the specific implementation process, just string together what this book wants to talk about, and focus on what I think is important. If you want to learn more, you can read this book directly, or you can search for related articles to read through some concepts in the text.

The overall structure of the book

Spring Boot is a new framework created on the basis of the Spring framework. Its design purpose is to simplify the construction and development process of Spring applications. It not only has all the excellent features of Spring, but also has the following remarkable features:

  • Provide easier use and rapid development skills for Spring development;
  • Has an out-of-the-box default configuration function, which can be automatically configured according to project dependencies;
  • Has a more powerful service system, including embedded services, security, performance indicators, monitoring and inspection, etc.;
  • XML configuration is no longer required, making the application more lightweight and flexible;

Version 1.0.0 was released in April 2014. There are currently 2 versions. The latest version of v1 is v1.5.10, and the latest version of v2 is v2.0.0.RC1.

This book gives a systematic and in-depth explanation of Spring Boot from the three dimensions of technology, practice and principle. The author gradually takes us to understand Spring Boot from the shallower to the deeper.

Part 1 - Technical Dimensions

It specifically introduces important technical knowledge such as Spring Boot entry, database usage and access performance improvement, interface design, security design, etc., focusing on practicality, to help us quickly grasp the development method and essence of Spring Boot, and integrate it into production practice as soon as possible.

Part II - Practical Dimensions

Use actual cases in the production environment to explain how to use Spring Boot to develop distributed applications and cloud applications, and how to use microservices to build a highly available service platform.

Part III - Principle Dimension

From the source code level, it focuses on analyzing the implementation principles of Spring Boot's core functions such as program loading, automatic configuration, data management, Spring
Cloud's configuration management, discovery service, and load balancing service, helping us to have a deeper understanding of Spring Boot development and master its essence. .

I like the author's chapter arrangement very much. When learning new technologies in the future, you can follow this line of thinking.

Getting Started with Spring Boot

This chapter mainly introduces the configuration of the development environment, including installing JDK, installing IDEA, installing Maven, installing Git client, and creating a simple project to demonstrate how to use Spring Boot.

Create a project with Spring Initializr

IDEA provides a visual interface to create various types of projects. You can create Spring Boot projects as required by Spring Initializr.

Spring Initializr

a simple demo

After the project is created, an entry Applicaton class will be generated, and the following modifications will be made to provide the reset interface for users to access.

@SpringBootApplication
@RestController
public class BookPart1Application {

    @RequestMapping("/")
    String home(){
        return "hello";
    }

    public static void main(String[] args) {
        SpringApplication.run(BookPart1Application.class, args);
    }
}
Run and publish

Running a Spring Boot project is easy, just run it like a normal project.

If you want to publish to the online Tomcat container, you need to add a packaging plugin: spring-boot-maven-plugin, which can be packaged through mvn package.

Spring Boot configuration

You can create an application.properties or application.yml file in the project's resources folder, which will be published on the classpath and automatically read by Spring Boot. The author recommends using the application.yml file as it provides a structured and nested format.

server:
  tomcat:
    uri-encoding: UTF-8
  port: 80

use database

Using a database is the basis for developing basic applications, and Spring Boot provides access to the database at a higher level. This chapter illustrates the convenience provided by Spring Boot by introducing the use of MySQL, Redis, MongoDB, Neo4j.

Using MySQL

For traditional relational databases, Spring Boot uses the JPA repository to implement database operations. JPA is a standard specification that provides persistence for POJOs, that is, ordinary Java objects are persisted to the database through object-relational mapping.

The author introduces the use of MySQL through the idea of ​​"Entity Modeling" -> "Entity Persistence" -> "Test Program".

Entity modeling is to describe the corresponding relationship with the database through annotations, including the attributes of entities and the relationship between entities.

Entity persistence is a powerful function provided by Spring Data. By inheriting from the JpaRepository interface of the JPA repository, you can perform operations such as adding, deleting, modifying, querying, paging, and specifying sorted fields to the database without implementing it yourself.

public interface JpaRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
    List<T> findAll();

    List<T> findAll(Sort var1);

    List<T> findAll(Iterable<ID> var1);

    <S extends T> List<S> save(Iterable<S> var1);

    void flush();

    <S extends T> S saveAndFlush(S var1);

    void deleteInBatch(Iterable<T> var1);

    void deleteAllInBatch();

    T getOne(ID var1);

    <S extends T> List<S> findAll(Example<S> var1);

    <S extends T> List<S> findAll(Example<S> var1, Sort var2);
}

JPA also provides some rules for custom declaration methods, and these methods do not need to be implemented. JPA will implement these methods by proxy, which is very convenient.

Using Redis

Redis does not have the concept of table structure, so to realize the data access of MySQL database table in Redis, some conversion must be done. You can use JSON format text as the storage format for data exchange between Redis and Java ordinary objects.

Redis can be easily operated through RedisTemplate.

For the use of Redis, you can also combine the annotation methods (@Cacheable, @CachePut, @CacheEvict) with the method of calling the database, so there is no need to write a redis operation service class, and it is easier to use. However, you can only perform related operations on simple objects. For complex objects that want the entity User to contain a certain relationship, or other collections and list objects, you cannot use simple annotations to implement them, and you have to use RedisTemplate.

public class RoleService { 
    @Autowired 
    private RoleRepository roleRepository;
    @Autowired 
    private RoleRedis roleRedis;


    @Cacheable(value = "mysql:findById:role", keyGenerator = "simpleKey") 
    public Role findById(Long id) {
        return roleRepository.findOne(id);
    } 

    @CachePut(value = "mysql:findById:role", keyGenerator = "objectId") 
    public Role create(Role role) {
        return roleRepository.save(role);
    } 

    @CachePut(value = "mysql:findById:role", keyGenerator = "objectId") 
    public Role update(Role role) {
        return roleRepository.save(role);
    } 

    @CacheEvict(value = "mysql:findById:role", keyGenerator = "simpleKey") 
    public void delete(Long id) {
        roleRepository.delete(id);
    } 
}
Using MongoDB

MongoDB is a document-type NoSQL database, which has the advantages of large data volume and high concurrency, but the disadvantage is that it cannot establish entity relationships, and there is no transaction management mechanism.

MongoDB also has a resource library like using JPA, which introduces spring-data-mongodb and spring-boot-starter-hateoas dependency library, so I won't introduce it too much here.

Using Neo4j

Neo4j is a high-performance NoSQL graph database with full transactional features, as well as the advantages of traditional relational databases and the advantages of NOSQL databases.

Neo4j stores structured data on a graph. The attributes of each node in the graph represent the content of the data, and each directed edge represents the relationship of the data. It has no concept of table structure, its data is represented by the attributes of nodes.

For example, there are now two entities Actor and Movie, and their relationship is expressed as an actor playing a role in a movie. Then you can create two node entities, actor and movie, and a role relationship entity.
Neo4j example

It expresses the relationship between entities more vividly and aptly, and this entity-relationship model can be directly stored in the database without any transformation, which will greatly reduce the design work and communication costs.

Like JPA uses ORM, Neo4j uses object-graph mapping OGM for modeling.

@RelationshipEntity(type = "ACTS_IN") 
public class Role { 
    @GraphId 
    Long id;
    String role;
    @StartNode 
    Actor actor;
    @EndNode 
    Movie movie;

    public Role() { 
    } 

    public Role(Actor actor, Movie movie, String name) {
        this.actor = actor;
        this.movie = movie;
        this.role = name;
    } 
}

As can be seen from the above introduction, it is very simple and easy to use the database in the Spring Boot framework, mainly due to the powerful functions of the Spring Boot resource library. Spring Boot integrates third-party resources and turns complex operations into simple calls.

interface design

This chapter uses the Spring Boot framework to design the Web display interface, and uses the concept of MVC to perform hierarchical processing of data management, event control, and interface display to achieve multi-layer structure design. Those who have used the MVC framework are better understood, so I won't explain too much here.

The interface shows that the Thymeleaf template is used, which has not been touched before, so please explain briefly. Thymeleaf is a modern server-side Java template engine. Unlike JSP and FreeMarker, Thymeleaf's syntax is closer to HTML, and it also has good extensibility.

Improve database access performance

The performance bottleneck of application systems using relational databases is ultimately the database. This chapter improves database access performance in the following ways:

  • Using Druid
  • Extend JPA functionality
  • Cache with Redis
Using Druid

Druid is a relational database connection pool, an open source project of Alibaba, which has obvious advantages in monitoring, scalability, stability and performance. By using the Druid connection pool, the access performance of the database can be improved to a certain extent.

Extend JPA functionality

Using JPA, in the definition of the repository interface, not only can various methods be declared according to the methods agreed in its rules, but also the annotation @Query can be used to define some simple query statements and optimize SQL statements.

You can extend the existing JPA interface by customizing an interface, inheriting from JpaRepository. Custom interfaces must be assembled at program startup in order to function properly. Then, in the JPA configuration class, load the defined assembly class via @EnableJpaRepositories.

public interface UserRepository extends ExpandJpaRepository<User, Long> {
    @Query("select t from User t where t.name =?1 and t.email =?2")
    User findByNameAndEmail(String name, String email);

    @Query("select t from User t where t.name like :name")
    Page<User> findByName(@Param("name") String name, Pageable pageRequest);
}
Cache with Redis

"Using Redis" has been introduced earlier.

safety design

The security management of web applications mainly includes two aspects: on the one hand, user authentication, that is, the design of user login; on the other hand, user authorization, that is, the permission management of what operations a user can perform in an application system.

The design of permission management generally uses roles to manage, which roles are assigned to a user, and the permissions the user has. This chapter mainly uses spring-cloud-security for security management design.

When using it, you need to inherit spring-cloud-starter-parent and introduce spring-cloud-starter-security dependency.

Regarding the security management and various designs of the system, Spring Security has basically been implemented, and it can be used normally only after some configuration and reference. The specific implementation will not be repeated here.

I didn't show a lot of implementation details. On the one hand, it will be too long and the priority is not clear. On the other hand, the author has put all the code on github ( http://github.com/chenfromsz ).
In the future, I will practice it well in the company's projects, and I will talk about my own experience.

love story

 

 

Guess you like

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