自定义SpringBootApplication、Java代码启动Tomcat

1 自定义@DavidSpringBootApplication
package com.david.springboot;

import org.springframework.context.annotation.ComponentScan;

import java.lang.annotation.*;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@ComponentScan
public @interface DavidSpringBootApplication{

}
 
  

2、自定义SpringBootApplication

public class DavidSpringApplication {

    public static void run(Class clazz) {

        //1、创建一个容器
        AnnotationConfigWebApplicationContext applicationContext=new AnnotationConfigWebApplicationContext();
        applicationContext.register(clazz);
        applicationContext.refresh();


        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();

        for (String beanName:beanDefinitionNames) {
            System.out.println("beanName------------------>"+beanName);
        }

        //2、启动Tomcat
        System.out.println("startTomcat");
        startTomcat(applicationContext,"localhost",8080);

//        startTomcat();
        System.out.println("startTomcat end");
    }


    public static void startTomcat(WebApplicationContext webApplicationContext,String hostname, Integer port) {

        Tomcat tomcat = new Tomcat();

        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");

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

        Engine engine = new StandardEngine();
        engine.setDefaultHost(hostname);

        Host host = new StandardHost();
        host.setName(hostname);

        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);

        // 接收到的所有请求最终都会转发到 DispatcherServlet 上面去处理
        tomcat.addServlet(contextPath, "dispatcher", new DispatcherServlet(webApplicationContext));
        context.addServletMappingDecoded("/*", "dispatcher");


        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }


    }
}
 
 

你可能感兴趣的:(框架,springboot)