模拟springboot底层实现

工程介绍_哔哩哔哩_bilibili 

启动注解:

@Target(ElementType.TYPE)  //类注解
@Retention(RetentionPolicy.RUNTIME)  //运行时
@Documented
@Inherited
@ComponentScan  //springboot扫描bean,内部spring容器就会有独赢controller的bean
public @interface MySpringBootApplication {
}

run方法:

public class MySpringApplication {

    public static void run(Class clazz){
        //创建一个spring容器
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(clazz);  //配置类
        applicationContext.refresh();

        //启动tomcat
        startTomcat(applicationContext);
    }

    /**
     * 配置tomcat
     * WebApplicationContext:spring容器
     */
    public static void startTomcat(WebApplicationContext applicationContext){

        Tomcat tomcat = new Tomcat();

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

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

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

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

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

        //关键:向tomcat容器添加dispatcherServlet的servlet,DispatcherServlet需要很具接受的请求去匹配某个controller中的对应方法
        tomcat.addServlet(contextPath, "dispatcher",new DispatcherServlet(applicationContext));  //SpringMVC中的DispatcherServlet,其中还有所有controller和注解,applicationContext就是所有Controller的所有的bean
        context.addServletMappingDecoded("/*","dispatcher");  //接收的所有请求交给dispatcher处理

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

启动类:

@MySpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        MySpringApplication.run(MyApplication.class);
    }
}

测试类

@RestController
public class UserController {
    @GetMapping
    public String test(){
        return "xuyu";
    }
}

你可能感兴趣的:(java框架,spring,boot,java,spring)