Use Spring Boot to quickly build projects: reduce configuration and improve development efficiency

Use Spring Boot to quickly build projects: reduce configuration and improve development efficiency

1. Introduction to Spring Boot

Spring Boot is a sub-project based on Spring Framework, which aims to simplify the initialization process, development process and deployment process of Spring applications, and provide a fast and agile development environment. Spring Boot improves development efficiency from the following three aspects:

1 The origin of Spring Boot

The introduction of Spring Boot aims to simplify the development, deployment and operation of Spring applications. It adopts the concept that convention is greater than configuration, and provides several common project dependencies and automatic configuration by default, so that developers can get started with Spring more easily and build Spring projects with less time and effort.

2 Core features of Spring Boot

  • Simplified configuration: Spring Boot adopts the design idea of ​​"convention over configuration".
  • Automatic assembly: Spring Boot can automatically configure Spring applications based on project dependency information and provides many functions.
  • No code generation: Spring Boot does not require any code generation, and can generate runnable Spring applications through simple configuration.
  • Microservices: Spring Boot is well suited for building microservice applications.
  • Integration testing: Spring Boot supports fast integration testing, which is convenient for developers to perform unit testing and integration testing.

3 Advantages of Spring Boot

  • Fast startup: Spring Boot applications have a very fast startup speed, which can also reduce a lot of development time and cost.
  • Easy to deploy: Spring Boot applications can be packaged as jar packages or war packages for deployment.
  • Easy to maintain: Spring Boot applications use configuration files, which are easy to maintain.
  • Out of the box: Spring Boot provides many built-in functions in many daily developments, and in many cases no need to add additional third-party dependencies and plug-ins.
  • Rich ecosystem: The Spring Boot ecosystem is very rich, providing many excellent open source projects, such as Spring Cloud, Spring Data, etc.

2. Spring Boot Quick Build Project

Spring Boot provides a variety of project construction methods. In most cases, using Spring Initializr to create projects is the most popular.

1 Spring Boot project construction method

Create a project using Spring Initializr

Use Spring Initializr to quickly and easily create a new project for Spring Boot. Spring Initializr not only provides a web interface and a command line tool, but also provides many optional configuration options.

Create a project using the Spring Boot CLI

Spring Boot CLI is a command-line tool that can create and run Spring Boot applications through the command line. Spring Boot CLI is a good choice for developers who are familiar with the command line and do not want to create projects through the web interface.

Create a project using Spring Boot CLI and Groovy DSL

Groovy DSL is a Groovy-based DSL that can be used to create and run Spring Boot applications, which greatly improves developer productivity.

2 Spring Boot project structure introduction

According to the recommended structure of Spring Boot, it can be divided into four parts: main application class and configuration file, controller layer, service layer and data layer.

Application main class and configuration file

The main application class is the entry point of the Spring Boot application, and the database connection, port and other information are specified through the configuration file.

The configuration file is divided into application.properties and application.yml formats. The file format at the end is curly brackets or square brackets used to indicate the list in the yaml file format, which is not supported.

controller layer

The controller layer is responsible for receiving HTTP requests, processing HTTP responses, and calling the service layer, data layer, etc. for processing. Use the @RestController annotation to turn a Spring Boot application into a full web service.

service layer

The service layer is responsible for business processing, and calls related methods of the data layer for data operations. Generally, the @Service annotation is used to mark the service class.

data layer

The data layer is responsible for data storage and reading, and can use frameworks such as Spring Data JPA for data operations.

Spring Boot's automatic configuration principle

Spring Boot's automatic configuration can automatically configure Spring applications through dependency analysis and intelligent infrastructure style while maintaining the awareness of Spring developers. Spring Boot itself does not rely on code generation and complex configuration methods.

Spring Boot's automatic configuration features

The core principle of Spring Boot's automatic configuration is that convention is greater than configuration. Its characteristics are:

  • Limited overhead: Only automated configuration enabled automatically configures the application.
  • Security Principle: Spring Boot does not automatically enable infrastructure without explicit configuration.
  • Scalability: Applications can benefit from automatic configuration or disable configuration that is not useful to them.

Loading order of Spring Boot auto-configuration

When the @EnableAutoConfiguration annotation enables automatic configuration, Spring Boot will load the automatic configuration items sequentially according to certain rules until it is fully loaded. The automatic configuration loading sequence is as follows:

  1. spring-boot-autoconfigure.jar/META-INF/spring.factories的EnableAutoConfiguration。
  2. Bean definitions from META-INF/spring.factories automatically configured by the current application's classpath based on conditions.

3. Common technologies in Spring Boot development

1 MVC architecture of Spring Boot

1.1 The basic concept of Spring Boot MVC

Various technologies and frameworks are commonly used in the development and design of Spring Boot applications, among which Spring Boot's MVC architecture is a common development method. The architecture provides a model-view-controller (MVC) architecture that simplifies the development of web applications.

The application can be divided into three parts in the whole architecture:

  • 模型(Model): Responsible for data storage and transmission, and provide methods for data manipulation.
  • 视图(View): Used to display data, usually an HTML page.
  • 控制器(Controller): Receive user requests and perform corresponding operations.

In Spring Boot MVC, annotations are often used to @Controllermark controller classes, and annotations are used to @RequestMappingmark methods in controller classes to specify URL addresses that respond to requests. In the method, you can use @RequestParamor @PathVariableannotation to obtain request parameters or path parameters.

Code example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    
    @GetMapping("/{userId}")
    public String getUserInfo(@PathVariable Long userId, Model model) {
    
    
        // 根据userId从数据库中获取User对象信息
        User user = userService.getUserById(userId);
        // 将查询到的User对象信息添加到Model中
        model.addAttribute("userInfo", user);
        // 返回名为"userInfo.html"的视图页面
        return "userInfo.html";
    }

    @PostMapping("/{userId}/update")
    public String updateUser(@PathVariable Long userId, 
                             @RequestParam("userName") String userName,
                             @RequestParam("userAge") int userAge) {
    
    
        // 根据userId更新数据库中对应User对象的userName和userAge
        userService.updateUser(userId, userName, userAge);
        // 重定向到/users/{userId}接口进行查询
        return "redirect:/users/{userId}";
    }
}

1.2 Precautions for Spring Boot MVC development

  • When writing, @Controllerpay attention to the return type of each method as String type, and specify the view name to be returned or specify the redirected or forwarded address through the return value.
  • When developing an application, it is recommended to place JSP view files in /resources/templatesa directory, and place all static files (such as css, js, and pictures, etc.) in a /resources/staticdirectory.
  • When encountering complex data operation logic, you can use the Service layer to encapsulate specific business logic and reduce the burden on the controller.
  • When developing an application, you should make full use of Spring Boot's automatic configuration function to simplify the configuration work.

2 Spring Boot integrates MyBatis framework

MyBatis is a Java persistence layer framework that maps objects to database tables through XML or annotations. Spring Boot provides a very convenient way to integrate the MyBatis framework, enabling developers to perform data operations more efficiently and conveniently.

2.1 The configuration method of Spring Boot integrating MyBatis

When configuring Spring Boot to integrate the MyBatis framework, you can follow the steps below:

  • Make sure that related dependencies such as MyBatis and MyBatis-Spring have been configured.
  • Confirm that the database driver-related dependencies have been added to the pom.xml file.
  • Configure data source related information in the application.properties file.
  • Create a MyBatis mapping file or use annotations for data manipulation.

Data source configuration in application.properties:

# 数据库驱动配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 数据库连接信息配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456

2.2 Basic CRUD operations of MyBatis

To perform data operations through the MyBatis framework, you need to write mapping files or annotations, and use the methods of the SqlSession interface to execute SQL statements. The basic CRUD operations of MyBatis are as follows:

  • Query data operation: Use the select query statement, which can be implemented by annotation or XML.
  • Insert data operation: use the insert statement, which can be implemented by annotation or XML.
  • Update data operation: Use the update update statement, which can be implemented through annotations or XML.
  • Delete data operation: Use delete to delete the statement, which can be implemented by annotation or XML.

Basic CRUD operations of MyBatis:

<!-- 数据库表中的数据对象映射配置文件 -->
<!-- 查询操作(通过user_id查询对应的User对象信息) -->
<select id="getUserById" parameterType="long" resultMap="userResultMap">
    select * from t_user where user_id = #{userId}
</select>
<!-- 插入操作(插入一条新的User对象信息) -->
<insert id="insertUser" parameterType="User">
    insert into t_user(user_id,user_name,user_age) values(#{userId},#{userName},#{userAge})
</insert>
<!-- 更新操作(根据user_id更新对应的User对象信息) -->
<update id="updateUserById" parameterType="User">
    update t_user set user_name = #{userName}, user_age = #{userAge} where user_id = #{userId}
</update>
<!-- 删除操作(根据user_id删除对应的User对象信息) -->
<delete id="deleteUserById" parameterType="long">
    delete from t_user where user_id = #{userId}
</delete>

3 Spring Boot integrates Spring Security framework

Spring Security is a Spring Framework-based security framework that can provide applications with security functions such as authentication and access control. Spring Boot provides a very convenient way to integrate the Spring Security framework, enabling developers to develop secure applications more efficiently and conveniently.

3.1 Spring Security's security authentication mechanism

Spring Security's security authentication mechanism includes user-defined user and password authentication methods, and supports multiple user information authentication methods based on memory, LDAP, and JDBC. In Spring Boot applications, security authentication information can be configured through annotations.

Spring Security's security authentication configuration:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    @Autowired
    private AuthUserDetailServiceImpl authUserDetailService;
    @Autowired
    private AuthAccessDeniedHandler accessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
    
        http.authorizeRequests()
                .antMatchers("/", "/index").permitAll()  // 设置首页和登录页允许匿名访问
                .antMatchers("/admin/**").hasRole("ADMIN")  // 设置/admin下的URL需要ADMIN角色才可以访问
                .anyRequest().authenticated()  // 其他URL都需要身份认证
                .and()
                .formLogin()
                .loginPage("/login") // 设置登录页面
                .defaultSuccessUrl("/index") // 登录成功后默认跳转的页面
                .failureUrl("/login?error")
                .permitAll()
                .and()
                .logout()
                .permitAll()
                .and()
                .exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler); // 设置异常处理器
        http.csrf().disable(); // 关闭csrf保护
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
        auth.userDetailsService(authUserDetailService).passwordEncoder(new BCryptPasswordEncoder());
    }
}

3.2 Common configuration methods of Spring Security

The common configuration methods of Spring Security mainly include the following aspects:

  • Configure the memory-based user information authentication method.
  • Configure the file-based user information authentication mode.
  • Configure a database-based user information authentication method.
  • Configure role-based access control.
  • Configure the HTTPS access method.

Memory-based user information authentication method:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    
    
        auth.inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER")
                .and()
                .withUser("admin").password("{noop}password").roles("USER", "ADMIN");
    }
}

4. Deployment and packaging of Spring Boot project

1 Packaging method of Spring Boot project

1.1 Packaging method of jar package

The common packaging method when using Spring Boot to develop applications is to package them into an executable jar package and start the application through the command line or script. It can be packaged with the following command:

mvn clean package

A jar package named after the application name and version number will be generated under the target directory. At the same time, you need to add a plug-in in the pom.xml file, and specify the packaging type as jar.

Configure the jar package packaging method in the pom.xml file:

<!-- 打包方式为jar -->
<packaging>jar</packaging>

<!-- jar包打包插件的配置 -->
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

1.2 Packaging method of war package

If you need to deploy a Spring Boot application into a web container, you can package the application into a war package. It can be packaged with the following command:

mvn clean package -Dmaven.test.skip=true

A war package named after the application name and version number will be generated under the target directory. At the same time, you need to add a plug-in in the pom.xml file, and specify the packaging type as war.

Configure the war package packaging method in the pom.xml file:

<!-- 打包方式为war -->
<packaging>war</packaging>

<!-- war包打包插件的配置 -->
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

2 Deployment method of Spring Boot project

2.1 Deployment in the traditional way

To deploy applications to web containers in the traditional way, various web containers such as Tomcat and Jetty can be used. The specific deployment steps are as follows:

  1. Copy the war package to the WebApps directory in the Web container.
  2. Start the web container and check the application startup status in the console.
  3. You can access the application by accessing the URL address provided by the web container through a browser.

2.2 Deployment method of Docker container

Docker container is a lightweight virtualization technology that can package applications into a mirror image and deploy and run them in different environments. Using Docker containers can quickly deploy applications, avoiding the problems of environment differences and dependency conflicts.

The specific deployment steps are as follows:

  1. Create a Dockerfile, specify the base image and the deployment method of the application, and package the application into an image file.
  2. Build a Docker image, and package the configuration parameters and applications in the Dockerfile into an image file.
  3. Run the Docker container, start the application and map the container to an external port, which can be accessed through a browser to access the external port.

The configuration of the Dockerfile file:

# 指定基础镜像
FROM openjdk:8-jdk-alpine

# 构建应用程序
COPY ./target/myapplication.jar /app/

# 暴露端口
EXPOSE 8080

# 启动应用程序
CMD ["java", "-jar", "/app/myapplication.jar"]

5. Summary and review

1 The development trend of Spring Boot

With the gradual maturity and wide application of Spring Boot, its development trend has become more and more obvious. In the future, Spring Boot will continue to develop in the direction of more efficient, convenient, safe, and intelligent, and continue to expand the application scenarios and application scope.

2 Evaluation of the advantages and disadvantages of Spring Boot

The advantages of Spring Boot mainly include:

  • Provides an extremely easy way to develop and deploy applications.
  • Integrates numerous Spring ecosystem components, reducing development difficulty and dependency conflicts.
  • Easy to realize automatic configuration and custom configuration.
  • Provides comprehensive testing and debugging tools.

The disadvantages of Spring Boot mainly include:

  • Not suitable for the complex needs of large enterprise applications.
  • Due to the potential risks of automatic configuration, some customized development requirements cannot be well realized.

Guess you like

Origin blog.csdn.net/u010349629/article/details/130673472