Spring Boot series (1) ---- Detailed introduction to Spring Boot

Introduction to Spring Boot

  Spring BootUsed to simplify Springapplication development, the convention is greater than the configuration, and the complex is simplified, just run can create an independent, product-level application .
  With the advent of the Spring Family Bucket era, SpringBoot has brought us a J2EE one-stop solution and SpringClouda distributed overall solution . From then on, we can use to SpringBootquickly develop projects based on the Spring framework. Because SpringBootthere are many out-of-the-box Starterdependencies around, it is very convenient for us to develop business code without paying too much attention to the configuration of the framework, but only to the business. That's it .

SpringBoot advantages

  • Quickly create standalone Spring projects and integrate with mainstream frameworks
  • Using the embedded Servlet container, the application does not need to be marked as a WAR package
  • Starters automatic dependency and version control
  • A large number of automatic configurations to simplify development, and you can also modify default values
  • No need to configure XML, no code generation, out of the box
  • Run-time application monitoring in a quasi-production environment
  • Natural integration with cloud computing

Microservice

  Speaking of SpringBoot, the service would have to mention micro, micro service is an architectural style, it can be understood as a small service , these services by HTTPway exchange . Each functional element is ultimately a software unit that can be independently replaced and independently upgraded ; there is no official definition of microservices. It is difficult to describe microservices directly. We can understand what microservices are by comparing traditional WEB applications. , The traditional application becomes a "single application": ALL IN ONE. Refer to the microservice documentation for details

Insert picture description here

  Monolithic applications are of that kind. The core is divided into business logic, adapters, and APIs or WEB interfaces accessed through UI. Business logic defines business processes, business rules, and domain entities. Adapters include database access components, message components, and access interfaces. All these things are integrated together, which looks very powerful, but in fact it is very messy.

  The microservice architecture has many important advantages, and it solves the problem of complexity . It decomposes a single application into a set of services. Although the total amount of functionality remains the same, the application has been broken down into manageable modules or services. These services define clear RPC or message-driven API boundaries. The microservice architecture strengthens the level of application modularity, which is difficult to achieve through a monolithic code base. Therefore, the development of microservices is much faster and easier to understand and maintain.
Insert picture description here

Implement a HelloWord application

Next, we first get started with a simple application, and then I will explain some SpringBoot configuration and use based on this simple application.

Environmental description

  • JDK1.8
  • Above SpringBoot1.7, I use SpringBoot2.4.3.
  • Above Maven3.3: I am using 3.6.3 here
  • Idea used by IDE

After installing Maven, remember to change the default JDK of Maven to 1.8, that is, in the conffolder where Maven is installed , open it setting.xml, and change it to the following configuration

<profile>
		<id>jdk-1.8</id>
		<activation>
			<activeByDefault>true</activeByDefault>
			<jdk>1.8</jdk>
		</activation>
		<properties>
			<maven.compiler.source>1.8</maven.compiler.source>
			<maven.compiler.target>1.8</maven.compiler.target>
			<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
		</properties>
	</profile>

Realize the function

A function, the browser sends a hello request, the server accepts the request and processes it, and responds to the HelloWorld string

Specific steps

  • Create Maven project
  • Import dependencies related to SpringBoot
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>
        <relativePath/>
    </parent>
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <!-- 这个插件,可以将应用打包成一个可执行的jar包;-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  • Write a main program; start the Spring Boot application
/**
 * @Author: zhang
 * @Descripetion:  @SpringBootApplication 来标注一个主程序类,说明这是一个Spring Boot应用
 **/
@SpringBootApplication
@RestController
public class HelloWorldApplication {
    
    

    public static void main(String[] args) {
    
    
        // Spring应用启动起来
        SpringApplication.run(HelloWorldApplication.class,args);
    }
  • Write related Controller, Service
@Controller
public class HelloController {
    
    

    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
    
    
        return "helloWorld";
    }
}

Once the code is written, run it directly. You heard it right. You don't need to do anything. Just run it directly. After running, you can directly access it in the browser and you will find success.
Insert picture description here

SpringBoot simplifies deployment

It is so convenient and simple from creation to operation. Before proceeding with code analysis and explanation, I would like to say more, that is, package deployment. Questions will be raised at this time, hey, when I just created it, it seems like Tomcat and the like were not installed and configured, and the war package was not opened. Why did it run? Let alone deployment. The SpringBoot project can be marked as a jar package, and then the jar package can be run directly without the need to install the operating environment, and the program can be started, which is very portable. We can use the Maven command to package, or directly use Idea to package. The Maven command can be directly searched online. Here I demonstrate that it is convenient to use Idea to package. The specific operation is as follows. There is in the Idea sidebar Maven Projects, click to open, and then click to packagerun to package :

Insert picture description here
Wait for the end of the operation, in the log, as shown in the following figure:
Insert picture description here
Insert picture description here
paste the packaged jar package to the desktop, then open the command line, and execute the command to run it. The
Insert picture description here
operation is successful, and then you can access it directly in the browser.

Hello World Exploration

POM file

Parent project

	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>
        <relativePath/>
    </parent>
    

  

His parent project is:

	<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.4.3</version>
  </parent>

He comes to really manage Spring Bootall the dependency versions in the application;
Spring Bootthe version arbitration center; in the future, we import dependencies by default without writing the version; (dependencies that are not dependenciesmanaged in it naturally need to declare the version number)

Launcher

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

spring-boot-starter-web:
spring-boot-starter: Spring-boot scene starter; helped us import the components that the web module depends on for normal operation;

Spring Boot extracts all the functional scenarios and makes them one by one starters(starters). All the dependencies of these starter-related scenarios need to be imported into the project. Import the launcher of any scene for what function you want to use. For specifics, you can go to the official documents

Main program class, main entry class

@SpringBootApplication
@RestController
public class HelloWorldApplication {
    
    

    public static void main(String[] args) {
    
    
        // Spring应用启动起来
        SpringApplication.run(HelloWorldApplication.class,args);
    }

@SpringBootApplication:

The Spring Boot application marking on a certain class indicates that this class is the main configuration class of SpringBoot, and SpringBoot should run the main method of this class to start the SpringBoot application;

We can click into this comment to have a look. " 按住Ctrl+左键"

@Target({
    
    ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {
    
    @Filter(
    type = FilterType.CUSTOM,
    classes = {
    
    TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {
    
    AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
    
    

@SpringBootConfiguration:

Configuration class of Spring Boot ;

  • Marked on a certain class, it means that this is a Spring Boot configuration class;

  • Continue to click into this @SpringBootConfiguration class:

    • @Configuratio: Mark this annotation on the configuration class;
    • Configuration class-----configuration file; configuration class is also a component in the container ;@Component

@EnableAutoConfiguration:

Turn on the automatic configuration function ;

  • What we need to configure before, Spring Boot helps us automatically configure;
  • @EnableAutoConfigurationTell SpringBoot to turn on the automatic configuration function; so that the automatic configuration can take effect; click to view
@AutoConfigurationPackage
@Import({
    
    AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    
    
  • @AutoConfigurationPackage: Automatic configuration package. (Click to view)
  • @Import({Registrar.class})
    • The bottom-level annotation of pring @Import, import a component into the container; the imported component is made by AutoConfigurationPackages.Registrar.class;Scan all components in the package of the main configuration class (class marked by @SpringBootApplication) and all sub-packages below to the Spring container;

AutoConfigurationImportSelector

Import components into the container ;
AutoConfigurationImportSelector:Selector of which components to import; Return all components that need to be imported in the form of full class names; These components will be added to the container; Many automatic configuration classes will be imported into the container ( xxxAutoConfiguration); is to import all the components needed for this scene into the container, and configure these components;
after clicking into this class, find the following method, and then interrupt the debug. You can see a lot of components in the console:
Insert picture description here
Insert picture description here
With the automatic configuration class, we don't need to manually write configuration injection functional components, etc.;

Spring Boot META-INF/spring.factoriesobtains the EnableAutoConfigurationspecified values from the classpath when it starts , and imports these values ​​into the container as an auto-configuration class. The auto-configuration class will take effect and help us with the auto-configuration work ;

In the past we needed to configure things by ourselves, now the automatic configuration class helps us; J2EE's overall integrated solution and automatic configuration are all available spring-boot-autoconfigure-1.5.9.RELEASE.jar;

Insert picture description here

This is the end of the analysis of the helloworld program, let's take a look at how to quickly create a SpringBoot project

Quickly create a SpringBoot project

Before we created a project, we first created a Maven project, and then imported the related Springboot dependencies, but in fact, we can use Idea to create a project in idea, to help us automatically create the springboot project that we need related dependencies.

IDEA: Use Spring Initializer to quickly create a project

Insert picture description here
Insert picture description here
Insert picture description here
In this way, the quick creation of our springboot is complete. You can go and take a look at the pom.xml file, the contents have been automatically fixed for us.

What I want to explain here is that under the resources in the project created by idea, three things will be automatically created for us. I will explain here.

  • static: Save all static resources js css images;;
  • templates: Save all template pages; (Spring Boot default jar package uses embedded Tomcat, and JSP pages are not supported by default); template engine ( freemarker、thymeleaf) can be used ;
  • application.properties: Configuration file of Spring Boot application; some default settings can be modified;

This concludes the introduction of springboot.

Guess you like

Origin blog.csdn.net/weixin_43844418/article/details/113923837
Recommended