简单手写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);
}
}
评论区