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.
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,
Access UserController
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
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
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!

Canal工作原理Canal模拟MySQLslave的交互协议,伪装自己为MySQLslave,向MySQLmaster发送dump协议MySQLmaster收到dump请求,开始推送binarylog给slave(也就是Canal)Canal解析binarylog对象(原始为byte流)MySQL打开binlog模式在MySQL配置文件my.cnf设置如下信息:[mysqld]#打开binloglog-bin=mysql-bin#选择ROW(行)模式binlog-format=ROW#配置My

前言SSE简单的来说就是服务器主动向前端推送数据的一种技术,它是单向的,也就是说前端是不能向服务器发送数据的。SSE适用于消息推送,监控等只需要服务器推送数据的场景中,下面是使用SpringBoot来实现一个简单的模拟向前端推动进度数据,前端页面接受后展示进度条。服务端在SpringBoot中使用时需要注意,最好使用SpringWeb提供的SseEmitter这个类来进行操作,我在刚开始时使用网上说的将Content-Type设置为text-stream这种方式发现每次前端每次都会重新创建接。最

一、手机扫二维码登录的原理二维码扫码登录是一种基于OAuth3.0协议的授权登录方式。在这种方式下,应用程序不需要获取用户的用户名和密码,只需要获取用户的授权即可。二维码扫码登录主要有以下几个步骤:应用程序生成一个二维码,并将该二维码展示给用户。用户使用扫码工具扫描该二维码,并在授权页面中授权。用户授权后,应用程序会获取一个授权码。应用程序使用该授权码向授权服务器请求访问令牌。授权服务器返回一个访问令牌给应用程序。应用程序使用该访问令牌访问资源服务器。通过以上步骤,二维码扫码登录可以实现用户的快

我们使用jasypt最新版本对敏感信息进行加解密。1.在项目pom文件中加入如下依赖:com.github.ulisesbocchiojasypt-spring-boot-starter3.0.32.创建加解密公用类:packagecom.myproject.common.utils;importorg.jasypt.encryption.pbe.PooledPBEStringEncryptor;importorg.jasypt.encryption.pbe.config.SimpleStrin

1.springboot2.x及以上版本在SpringBoot2.xAOP中会默认使用Cglib来实现,但是Spring5中默认还是使用jdk动态代理。SpringAOP默认使用JDK动态代理,如果对象没有实现接口,则使用CGLIB代理。当然,也可以强制使用CGLIB代理。在SpringBoot中,通过AopAutoConfiguration来自动装配AOP.2.Springboot1.xSpringboot1.xAOP默认还是使用JDK动态代理的3.SpringBoot2.x为何默认使用Cgl

知识准备需要理解ApachePOI遵循的标准(OfficeOpenXML(OOXML)标准和微软的OLE2复合文档格式(OLE2)),这将对应着API的依赖包。什么是POIApachePOI是用Java编写的免费开源的跨平台的JavaAPI,ApachePOI提供API给Java程序对MicrosoftOffice格式档案读和写的功能。POI为“PoorObfuscationImplementation”的首字母缩写,意为“简洁版的模糊实现”。ApachePOI是创建和维护操作各种符合Offic

1.首先新建一个shiroConfigshiro的配置类,代码如下:@ConfigurationpublicclassSpringShiroConfig{/***@paramrealms这儿使用接口集合是为了实现多验证登录时使用的*@return*/@BeanpublicSecurityManagersecurityManager(Collectionrealms){DefaultWebSecurityManagersManager=newDefaultWebSecurityManager();

一、定义视频上传请求接口publicAjaxResultvideoUploadFile(MultipartFilefile){try{if(null==file||file.isEmpty()){returnAjaxResult.error("文件为空");}StringossFilePrefix=StringUtils.genUUID();StringfileName=ossFilePrefix+"-"+file.getOriginalFilename(


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version

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.

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!
