侧边栏壁纸
  • 累计撰写 22 篇文章
  • 累计创建 10 个标签
  • 累计收到 5 条评论

目 录CONTENT

文章目录

简单手写springboot启动类

AF
AF
2024-02-19 / 0 评论 / 0 点赞 / 31 阅读 / 1984 字

简单手写springboot 启动类

public class AfSpringbootApplication {
    public static void run(Class clazz) {
        // 创建容器
        AnnotationConfigWebApplicationContext annotationConfigApplicationContext = new AnnotationConfigWebApplicationContext();
        annotationConfigApplicationContext.register(clazz); // 获取类的包路径,将bean托管给容器
        annotationConfigApplicationContext.refresh();
        createTomcat(annotationConfigApplicationContext);
    }
    // 创建tomcat和servlet
    private static void createTomcat(WebApplicationContext webApplicationContext) {
        Tomcat tomcat = new Tomcat();
        Server server = tomcat.getServer();
        
        Service service = server.findService("Tomcat");

        Connector connector = new Connector();
        connector.setPort(8081);

        StandardEngine standardEngine = new StandardEngine();
        standardEngine.setDefaultHost("localhost");

        StandardHost standardHost = new StandardHost();
        standardHost.setName("localhost");

        String contextPath = "";
        StandardContext standardContext = new StandardContext();
        standardContext.setPath(contextPath);
        standardContext.addLifecycleListener(new Tomcat.FixContextListener());

        standardHost.addChild(standardContext);
        standardEngine.addChild(standardHost);

        service.setContainer(standardEngine);
        service.addConnector(connector);

        tomcat.addServlet(contextPath, "dispatcher", new DispatcherServlet(webApplicationContext));
        standardContext.addServletMappingDecoded("/*", "dispatcher");

        try {
            tomcat.start();
        } catch (LifecycleException e) {
            throw new RuntimeException(e);
        }
    }
}
// 本来应该弄一个启动类注解的,懒得写,就直接在这个类把注解写在这了
@ComponentScan
public class StartApp {
    public static void main(String[] args) {
        AfSpringbootApplication.run(StartApp.class);
    }
}

0

评论区