Spring MVC、Servlet 3.0:如何创建资源引用

Spring MVC, Servlet 3.0: how to create resource-ref

我正在使用 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;

}

我正在创建这个 spring 应用程序,方法是从 java 应用程序复制 Servlet < 3.0,所以有一个 web.xml 包含关于这个部分 数据来源:

<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 Specification Version 3.0"。 它说的是@Resource:

The @Resource annotation is used to declare a reference to a resource such as a data source... This annotation is equivalent to declaring a resource-ref...

@Resource example:

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

In the example code above, a servlet, filter, or listener declares a field catalogDS of type javax.sql.DataSource for which the reference to the data source is injected by the container prior to the component being made available to the application. The data source JNDI mapping is inferred from the field name “catalogDS” and type (javax.sql.DataSource). Moreover, the catalogDS resource no longer needs to be defined in the deployment descriptor.

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

public class WebConfig extends WebMvcConfigurerAdapter {

完全正确的位置?

我通过扩展

实现了一个监听器
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