本文主要是介绍自定义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、启动TomcatSystem.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();}}
}
这篇关于自定义SpringBootApplication、Java代码启动Tomcat的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!