【发布时间】:2014-11-27 18:34:45
【问题描述】:
我正在学习 Spring MVC。我正在尝试使用@Resource 注入数据源。是这样的:
Tomcat的web.xml:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
context.xml:
Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="sa" password="" driverClassName="org.h2.Driver"
url="jdbc:h2:tcp://localhost/~/test"/>
控制器代码(使用Spring MVC框架):
@Controller
public class SimpleControllerAnnotation {
//@Resource(name="dataSource")
@Resource(name="jdbc/TestDB")
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
//@Resource(name="dataSource")
@Resource(name="jdbc/TestDB")
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@RequestMapping("/testDataSource")
public ModelAndView testDataSource() {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String name = null;
String ID = null;
try {
con = dataSource.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery("select ID, name from STUDENT");
while(rs.next()){
name = rs.getString("name");
ID = rs.getString("ID");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
ModelAndView mw = new ModelAndView("TestDataSourceForm");
mw.addObject("DataSourceValue",dataSource);
mw.addObject("Name",name);
mw.addObject("ID",ID);
return mw;
}
在这段代码中,我使用@Resource 来注入我打算从Tomcat 中“获取”的DataSource,它是我在Tomcat 中设置的(上面共享的web.xml 和context.xml)。
当我运行这个程序时,我得到以下异常:
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'simpleControllerAnnotation': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'jdbc/TestDB' is defined
jdbc/TestDB是我在Tomcat中设置的DataSource。
我有以下疑问:
1) 是否可以将我们在 Tomcat 中创建的 DataSource 以这种方式注入?或者我们必须使用 JNDI 查找。在我在互联网上阅读的一篇文章中,有人说 JNDI 查找有点过时了,现在依赖注入是首选方式。
2) 一般而言,最佳实践是在应用服务器/Web 容器中设置数据源还是在应用程序本身中进行管理。从我读到的帖子来看,最好让 App server/Container 来管理这个。
非常感谢您对解决此错误的任何帮助。
【问题讨论】:
-
你真的在两个地方使用@Resource 还是拼写错误?否则它看起来像mkyong.com/tomcat/how-to-configure-mysql-datasource-in-tomcat-6
-
@sodik:我试过这个,我仍然得到异常。
-
Spring MVC 除了 web.xml 和 context.xml(tomcat 的)之外,还有自己的配置文件。我相信上面链接中的示例不适用于 Spring MVC 框架。我试过但是得到了同样的例外。任何有助于解决此问题的指针表示赞赏。
标签: java spring spring-mvc tomcat datasource