http://static.springsource.org/spring/docs/current/spring-framework-reference/html/jdbc.html
以上是官方教程,讲得非常详细,两种方法。
但是,有一点没讲,使用这种办法,必须要保证这个类在 bean的管理之下,就是说,写在controller里面,然后实例也标记autowired。
你自己定义实例是没用的,不属于bean管理的范畴,所以autowired 的 setDataSource方法不会被调用!
最后,我的办法是,获得dataSource
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(InitServletContext.getServletContext()); DataSource dataSource = (DataSource) ac.getBean("dataSource"); this.jdbcTemplate = new JdbcTemplate(dataSource);
http://stackoverflow.com/questions/12862203/autowired-and-service-working-from-controller-but-not-from-a-different-package
@Component public class InitServletContext implements ServletContextAware{ static ServletContext ServletContext; @Override public void setServletContext(ServletContext servletContext) { ServletContext = servletContext; } public static ServletContext getServletContext() { return ServletContext; } }
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- 连接MySQL--> <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"></beans:property> <beans:property name="url" value="jdbc:mysql://localhost:3306/piano_db"></beans:property> <beans:property name="username" value="root"></beans:property> <beans:property name="password" value="root"></beans:property> </beans:bean>