Spring高级--容器实现-ApplicationContext实现(二)
一、AnnotationConfigServletWebServerApplicationContext
Spring boot 中 servlet web 环境容器(新)
1、场景利用AnnotationConfigServletWebServerApplicationContext 手写一个简单的web应用
代码
package com.mangoubiubiu.show; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletRegistrationBean; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebApplicationContext; import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.mvc.Controller; import java.util.Arrays; public class AplicontextInterface { public static void main(String[] args) { testAnnotationConfigServletWebServerApplicationContext(); } //较为经典的容器,基于java配置类来创建,用于web环境 private static void testAnnotationConfigServletWebServerApplicationContext() { AnnotationConfigServletWebServerApplicationContext context= new AnnotationConfigServletWebServerApplicationContext(WebConfig.class); } @Configuration static class WebConfig{ //tomcat 服务器 @Bean public ServletWebServerFactory servletWebServerFactory(){ return new TomcatServletWebServerFactory(); } //创建servlet对象 @Bean public DispatcherServlet dispatcherServlet(){ return new DispatcherServlet(); } //把servlet注册到tomcat服务器上去 @Bean public DispatcherServletRegistrationBean dispatcherServletRegistrationBean(DispatcherServlet dispatcherServlet){ return new DispatcherServletRegistrationBean(dispatcherServlet,"/show/"); } @Bean("/hello") public Controller controller1(){ return (request, response) -> { response.getWriter().println("hello"); return null; }; } } }
main方法启动
本文作者:KwFruit
本文链接:https://www.cnblogs.com/mangoubiubiu/p/16089625.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
Spring
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步