Home > Java > javaTutorial > What is the underlying principle of SpringBoot?

What is the underlying principle of SpringBoot?

王林
Release: 2023-05-11 12:40:06
forward
859 people have browsed it

Handwritten springboot

In daily development, you only need to introduce the following dependencies to develop Servlet for access.

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

So how is this done? Let’s find out today

First create a new maven project rick-spring-boot, and create two sub-projects namely spring-boot and user. The spring-boot project is to simulate handwriting a simple springboot, and user is Used to test handwritten spring-boot.

What is the underlying principle of SpringBoot?

user project-test project

The user project contains pom.xml, UserController and UserService

<dependencies>
    <dependency>
      <groupId>com.rick.spring.boot</groupId>
      <artifactId>spring-boot</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency>
  </dependencies>
Copy after login
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/user")
    public String getUser() {
        return userService.getUser();
    }
}
@Service
public class UserService {
    public String getUser() {
        return "rick";
    }
}
Copy after login

as well as the startup class RickApplication of the user project , and RickSpringApplication.run() requires handwritten startup classes and @RickSpringBootApplication annotations, which need to be implemented in the spring-boot project.

import com.rick.spring.boot.RickSpringApplication;
import com.rick.spring.boot.RickSpringBootApplication;
@RickSpringBootApplication
public class RickApplication {
    public static void main(String[] args) {
        RickSpringApplication.run(RickApplication.class);
    }
}
Copy after login

Springboot project

First let’s look at what the RickSpringApplication.run(RickApplication.class) method needs to do:

(1) Create a spring container and pass in The class is registered in the spring container

(2) Start the web service, such as tomcat, to process the request, and distribute the request to the Servlet for processing through DispatchServlet.

public class RickSpringApplication {
    public static void run(Class clz) {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(clz);
        context.refresh();
        start(context);
    }
    public static void start(WebApplicationContext applicationContext) {
        System.out.println("start tomcat");
        Tomcat tomcat = new Tomcat();
        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");
        Connector connector = new Connector();
        connector.setPort(8081);
        Engine engine = new StandardEngine();
        engine.setDefaultHost("localhost");
        Host host = new StandardHost();
        host.setName("localhost");
        String contextPath = "";
        Context context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());
        host.addChild(context);
        engine.addChild(host);
        service.setContainer(engine);
        service.addConnector(connector);
        tomcat.addServlet(contextPath, "dispatcher", new DispatcherServlet(applicationContext));
        context.addServletMappingDecoded("/*", "dispatcher");
        try {
            tomcat.start();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }
}
Copy after login

RickApplication is modified by the @RickSpringBootApplication annotation. From the following code, we can see that RickApplication is a configuration class. After being registered to the spring container, spring will parse this class.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Configuration
@ComponentScan
public @interface RickSpringBootApplication {
}
Copy after login

Start the main method of the user project RickApplication,

What is the underlying principle of SpringBoot?

Access UserController

What is the underlying principle of SpringBoot?

This is a simple The spring-boot project is integrated.

Automatic configuration

Realize switching between tomcat and jetty

When using springboot, if we do not want to use tomcat as the request processing service, but jetty or other web services, Usually you only need to exclude the relevant tomcat dependencies, and then introduce the jetty dependencies. This is the automatic assembly mechanism of springboot. Next, let’s take a look at how to implement it

Define a WebServer interface and two implementation classes (tomcat and jetty), and write the code to start the tomcat and jetty services

public interface WebServer {
    void start();
}
public class JettyServer implements WebServer{
    @Override
    public void start() {
        System.out.println("start jetty");
    }
}
Copy after login
public class TomcatServer implements WebServer, ApplicationContextAware {
    private WebApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = (WebApplicationContext) applicationContext;
    }
    @Override
    public void start() {
        System.out.println("start tomcat");
        ...
        tomcat.addServlet(contextPath, "dispatcher", new DispatcherServlet(applicationContext));
        context.addServletMappingDecoded("/*", "dispatcher");
        try {
            tomcat.start();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }
}
Copy after login

Define the AutoConfiguration interface, Used to identify classes that need to be automatically assembled. Define another WebServerAutoConfiguration class, which is represented as a configuration class of spring. Finally, we need to import this class and let spring parse it. Then spring will parse the @Bean annotation method to load the Bean. Note that the following two methods also define the @RickConditionalOnClass annotation to determine whether the bean needs to be parsed. If the conditions are met, the bean will be parsed. That is, if the Class stored in Tomcat or Server is applied, the bean of the corresponding method will be parsed.

public interface AutoConfiguration {
}
@Configuration
public class WebServerAutoConfiguration implements AutoConfiguration {
    @Bean
    @RickConditionalOnClass("org.apache.catalina.startup.Tomcat")
    public TomcatServer tomcatServer() {
        return new TomcatServer();
    }
    @Bean
    @RickConditionalOnClass("org.eclipse.jetty.server.Server")
    public JettyServer jettyWebServer() {
        return new JettyServer();
    }
}
Copy after login

Look at the @RickConditionalOnClass annotation: When spring parses a method annotated with @RickConditionalOnClass, spring knows that it is modified by @Conditional, and will execute the match() method of RickOnClassConditional during parsing to determine whether the conditions for loading the bean are met. match() will try to load the passed class path name. If the relevant jar is introduced into the application, it will load successfully and return true. Otherwise, it will return false.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Conditional(RickOnClassConditional.class)
public @interface RickConditionalOnClass {
    String value();
}
public class RickOnClassConditional implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> annotation = metadata.getAnnotationAttributes(RickConditionalOnClass.class.getName());
        try {
            context.getClassLoader().loadClass((String) annotation.get("value"));
        } catch (ClassNotFoundException e) {
            return false;
        }
        return true;
    }
}
Copy after login

Introducing WebServerAutoConfiguration, the simplest and crudest way is to import this class through @Import(WebServerAutoConfiguration.class). But it is impossible for spring-boot to do this. It is definitely not good to write hundreds of automatic configurations in the code. Spring uses the SPI mechanism to create the following directories and files in the resources directory

What is the underlying principle of SpringBoot?

Define a class to implement the DeferredImportSelector interface, and implement selectImports(), and load the above files through the JDK's ServiceLoader the type. When importing this class through the @Import(WebServerImportSelector.class) annotation, spring will execute selectImports() when parsing the configuration class, thereby importing WebServerAutoConfiguration into the spring container, and spring will parse this configuration class.

public class WebServerImportSelector implements DeferredImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata metadata) {
        ServiceLoader<AutoConfiguration> load = ServiceLoader.load(AutoConfiguration.class);
        List<String> list = new ArrayList<>();
        for (AutoConfiguration loader : load) {
            list.add(loader.getClass().getName());
        }
        return list.toArray(new String[list.size()]);
    }
}
Copy after login

At this point, springboot can switch tomcat and jetty services only by modifying the maven dependency of the user project.

<dependency>
      <groupId>com.rick.spring.boot</groupId>
      <artifactId>spring-boot</artifactId>
      <version>1.0-SNAPSHOT</version>
      <exclusions>
        <exclusion>
          <groupId>org.apache.tomcat.embed</groupId>
          <artifactId>tomcat-embed-core</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.eclipse.jetty</groupId>
      <artifactId>jetty-server</artifactId>
      <version>9.4.43.v20210629</version>
    </dependency>
Copy after login

Restart the user project

What is the underlying principle of SpringBoot?

The above is the detailed content of What is the underlying principle of SpringBoot?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template