search
HomeJavajavaTutorialWhat is the underlying principle of SpringBoot?

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>

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>
@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";
    }
}

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);
    }
}

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();
        }
    }
}

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 {
}

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");
    }
}
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();
        }
    }
}

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();
    }
}

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;
    }
}

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()]);
    }
}

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>

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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

What does 'platform independence' mean in the context of Java?What does 'platform independence' mean in the context of Java?Apr 23, 2025 am 12:05 AM

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Can Java applications still encounter platform-specific bugs or issues?Can Java applications still encounter platform-specific bugs or issues?Apr 23, 2025 am 12:03 AM

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

How does cloud computing impact the importance of Java's platform independence?How does cloud computing impact the importance of Java's platform independence?Apr 22, 2025 pm 07:05 PM

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

What role has Java's platform independence played in its widespread adoption?What role has Java's platform independence played in its widespread adoption?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

How do containerization technologies (like Docker) affect the importance of Java's platform independence?How do containerization technologies (like Docker) affect the importance of Java's platform independence?Apr 22, 2025 pm 06:49 PM

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.