在将非 Spring 应用程序转换为 Spring Boot 时,希望在嵌入式 tomcat 中使用现有的 context.xml 文件。
使用 Spring Boot 1.5.1 和 Tomcat 8.5.11
TomcatEmbeddedServletContainerFactory 配置
@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
return new TomcatEmbeddedServletContainerFactory() {
@Override
protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) {
tomcat.enableNaming();
return super.getTomcatEmbeddedServletContainer(tomcat);
}
@Override
protected void postProcessContext(Context context) {
// Try-1 - Not Working
if (context instanceof StandardContext) {
StandardContext standardContext = (StandardContext) context;
standardContext.setCopyXML(true);
}
// Try-2 - Not Working
context.setConfigFile(Paths.get("/META-INF/context.xml").toFile().toURI().toURL());
// Try-3 - Working - But due to very large and multiple configuration, java config will be cumbersome
ContextResource resource = new ContextResource();
resource.setName("jdbc/myDB");
resource.setType(DataSource.class.getName());
resource.setAuth("Container");
resource.setProperty("username", "user111");
resource.setProperty("password", "password111");
resource.setProperty("driverClassName", "com.mysql.cj.jdbc.Driver");
context.getNamingResources().addResource(resource);
}
}
检查数据库连接的方法,
public void checkDb() {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource datasource = (DataSource) envContext.lookup("jdbc/myDB");
Connection con = datasource.getConnection();
}
那么如何在 Spring Boot 中加载现有的 context.xml。