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方法启动



浙公网安备 33010602011771号