【问题标题】:Spring Boot still requires resource-ref in web.xmlSpring Boot 仍然需要 web.xml 中的资源引用
【发布时间】:2017-04-30 00:06:48
【问题描述】:

现在正在研究 Spring Boot 并希望正确执行它,因为使用 Java 配置并且最终没有任何 web.xml。所以,棘手的部分是生产环境需要一个经典的WAR 文件。

因此,我在我的 Maven pom.xmlfile 中指定了 WAR 包装,主应用程序类扩展 SpringBootServletInitializer

工作得很好。现在,棘手的部分是在生产环境中,Datasource 是通过JNDI 配置的。在经典的 Spring 应用程序中,您可以使用 resource-refweb.xml 中引用此依赖项,如下所示:

 <resource-ref>
    <res-ref-name>jdbc/DefaultDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
</resource-ref>

我所做的所有研究似乎都表明我可以摆脱 web.xml 并将其替换为相应的 context.xml 文件(在 META-INF 文件夹中):

   <Resource name="jdbc/DefaultDB"
          auth="Container"
          type="javax.sql.DataSource"
          factory="com.sap.jpaas.service.persistence.core.JNDIDataSourceFactory"/>

不幸的是,这不起作用:/

有趣的是,一个普通的 servlet3 Web 应用程序可以正常工作,请参阅 [https://github.com/steinermatt/servlet3-sample]

所以,我很想相信它对 Spring Boot 应用程序不起作用的根本原因与 Spring Boot 引导过程有关......所以,真的在寻找任何提示,关于它可能是什么的建议!!!

感谢任何帮助!

【问题讨论】:

  • 这里给出的解决方案stackoverflow.com/a/56663753/2163693 可能对遇到这个线程的人有用......它对我特别适用于这个 SCP neo 场景
  • 您找到解决方案了吗?伊恩 - 您是如何在链接答案中使用该解决方案的?

标签: spring spring-boot servlet-3.0


【解决方案1】:

默认情况下,嵌入式 Tomcat 中禁用 JNDI。

您可以使用以下代码在 tomcat 中启用 JNDI。以下代码将帮助您初始化 DataSource spring bean。

    @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) {
            ContextResource resource = new ContextResource();
            resource.setName("jdbc/myDataSource");
            resource.setType(DataSource.class.getName());
            resource.setProperty("driverClassName", "your.db.Driver");
            resource.setProperty("url", "jdbc:yourDb");

            context.getNamingResources().addResource(resource);
        }
    };
}

您可以使用自动连接在控制器中使用 DataSource bean。

@Autowired
private DataSource dataSource;

【讨论】:

    猜你喜欢
    • 2016-07-12
    • 2015-08-21
    • 2015-09-09
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 2017-09-21
    相关资源
    最近更新 更多