环境搭建
导入以下依赖:
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-core -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.44</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-jasper -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>9.0.44</version>
</dependency>
</dependencies>
编写AbstractAnnotationConfigDispatcherServletInitializer
实现类,
具体原理可参考:
public class QuickWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override //spring配置文件
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{AppConfig.class};
}
@Override //springmvc的配置文件
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{MvcConfig.class};
}
@Override //servlet映射
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
编写配置类,service,controller:
@ComponentScan("com.wj.service")
@Configuration
public class AppConfig {
}
@Configuration
@ComponentScan("com.wj.controller")
public class MvcConfig {
}
@RestController
public class TestController {
public TestController(){
System.out.println("MyController ...");
}
@Autowired
private ApplicationContext applicationContext;
@Autowired
private MyService myService;
@RequestMapping("test")
public String test() {
System.out.println(applicationContext);
return myService.test();
}
}
@Service
public class MyService {
public MyService(){
System.out.println("MyService...");
}
@Autowired
private ApplicationContext applicationContext;
public String test() {
return "hello spring mvc";
}
}
目录结构如下:
编写main方法
编写main方法,用于启动tomcat:
注意:
-
Tomcat 9.0 必须调用
tomcat.getConnector()
方法之后才会监听端口,否则一直会阻塞 -
Tomcat 8 必须在
tomcat.start()
后调用tomcat.getServer().await();
,否则main方法直接结束。
我这里用的是tomcat9依赖,所以按照下面这种写法就行了。
public static void main(String[] args) throws LifecycleException {
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
tomcat.setHostname("localhost");
tomcat.setBaseDir(".");
//设置contextPath和baseDir
tomcat.addWebapp("/boot", System.getProperty("user.dir") + "/src/main");
tomcat.getConnector();
tomcat.start();
}
启动日志如下:
访问接口:http://localhost:8080/boot/test
至此,springmvc整合嵌入式tomcat成功。