【问题标题】:Spring MVC, Servlet 3.0: how to create resource-refSpring MVC,Servlet 3.0:如何创建资源引用
【发布时间】:2015-12-06 09:17:08
【问题描述】:

我正在使用 Spring MVC (4.2.3) 和 Servlet 3.0 API,所以没有web.xml。

我的WebConfig.java如下:

...
import javax.servlet.ServletContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {...})
public class WebConfig extends WebMvcConfigurerAdapter {

@Autowired
ServletContext servletContext;

}

我通过从 java 应用程序复制来创建这个 spring 应用程序 Servlet

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

如何在我的 Spring MVC 应用程序中创建这样的设置,其中没有 web.xml?

与此同时,我查看了“Java Servlet 规范版本 3.0”。 它说关于@Resource:

@Resource 注解用于声明对资源的引用 比如一个数据源……这个注解相当于声明一个 资源引用...

@Resource 示例:

@Resource private javax.sql.DataSource catalogDS;
public getProductsByCategory() {
 // get a connection and execute the query
 Connection conn = catalogDS.getConnection();
..
}

在上面的示例代码中,servlet、过滤器或侦听器声明了一个 引用的 javax.sql.DataSource 类型的字段 catalogDS 数据源由容器在组件之前注入 可供应用程序使用。 从字段名称推断数据源 JNDI 映射 “catalogDS”和类型(javax.sql.DataSource)。此外,目录DS 资源不再需要在部署描述符中定义。

不幸的是,我不知道如何使用它以及如何将它连接到 Springs JDBCTemplate。是

public class WebConfig extends WebMvcConfigurerAdapter {

位置是否正确?

【问题讨论】:

    标签: spring spring-mvc servlet-3.0


    【解决方案1】:

    我通过扩展实现了一个监听器

    org.springframework.web.context.ContextLoaderListener
    

    并添加注释

    @WebListener.
    

    在那个监听器中

    @Resource private javax.sql.DataSource catalogDS;
    

    已成功填充。

    http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html http://docs.oracle.com/javaee/6/api/javax/servlet/annotation/WebListener.html http://docs.oracle.com/javaee/6/api/javax/annotation/Resource.html

    【讨论】:

    • 谢谢!但是据我所知 javax.servlet.ServletContextListener 是一个 servlet 容器托管组件,我需要 Spring 应用程序上下文中的 javax.sql.DataSource。
    猜你喜欢
    • 1970-01-01
    • 2014-03-08
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 2021-04-15
    • 2016-03-12
    • 1970-01-01
    相关资源
    最近更新 更多