栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

手写简易版springboot

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

手写简易版springboot

1、引入maven依赖


		
		
			org.apache.tomcat.embed
			tomcat-embed-core
			8.5.16
		
		
		
			org.springframework
			spring-web
			5.0.4.RELEASE
			compile
		
		
		
			org.springframework
			spring-webmvc
			5.0.4.RELEASE
			compile
		
		
		
			org.apache.tomcat
			tomcat-jasper
			8.5.16
		

2、加载SpringMVCDispatcherServlet

AbstractAnnotationConfigDispatcherServletInitializer这个类负责配置DispatcherServlet、初始化Spring MVC容器和Spring容器。getRootConfigClasses()方法用于获取Spring应用容器的配置文件,这里我们给定预先定义的RootConfig.classgetServletConfigClasses负责获取Spring MVC应用容器,这里传入预先定义好的WebConfig.classgetServletMappings()方法负责指定需要由DispatcherServlet映射的路径,这里给定的是"/",意思是由DispatcherServlet处理所有向该应用发起的请求。

public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	// 加载根容器
	protected Class[] getRootConfigClasses() {
		// TODO Auto-generated method stub
		return new Class[] { RootConfig.class };
	}

	// 加载SpringMVC容器
	protected Class[] getServletConfigClasses() {

		return new Class[] { WebConfig.class };
	}

	// SpringMVCDispatcherServlet 拦截的请求 /
	protected String[] getServletMappings() {

		return new String[] { "/" };
	}

}

3、加载SpringMVC容器

正如可以通过多种方式配置DispatcherServlet一样,也可以通过多种方式启动Spring MVC特性。原来我们一般在xml文件中使用元素启动注解驱动的Spring MVC特性。

@Configuration
@EnableWebMvc
@ComponentScan("com.wangcj.controller")
public class WebConfig extends WebMvcConfigurerAdapter {
}

4、RootConfig容器

@Configuration
@ComponentScan(basePackages = "com.wangcj")
public class RootConfig {
}

5、运行代码

public static void main(String[] args) throws ServletException, LifecycleException {
		start();
}

public static void start() throws ServletException, LifecycleException {
		// 创建Tomcat容器
		Tomcat tomcatServer = new Tomcat();
		// 端口号设置
		tomcatServer.setPort(9090);
		// 读取项目路径
		StandardContext ctx = (StandardContext) tomcatServer.addWebapp("/", new File("src/main").getAbsolutePath());
		// 禁止重新载入
		ctx.setReloadable(false);
		// class文件读取地址
		File additionWebInfClasses = new File("target/classes");
		// 创建WebRoot
		WebResourceRoot resources = new StandardRoot(ctx);
		// tomcat内部读取Class执行
		resources.addPreResources(
				new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/"));
		tomcatServer.start();
		// 异步等待请求执行
		tomcatServer.getServer().await();
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/340508.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号