zoukankan      html  css  js  c++  java
  • 关于spring mvc3, mysql, setDataSource, AutoWired

    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>
  • 相关阅读:
    css固定元素位置(fixed)
    【转】php 下载保存文件保存到本地的两种实现方法
    【转】关于URL编码/javascript/js url 编码/url的三个js编码函数
    IE6对png图片的处理
    用phpcms开发模块时中文乱码问题
    【转】MySQL数据类型和常用字段属性总结
    PHPCMS几个有用的全局函数
    PHPCMS系统常量
    PHPCMS系统使用的弹出窗口插件artDialog
    基础知识点(一)
  • 原文地址:https://www.cnblogs.com/Sorean/p/3023300.html
Copyright © 2011-2022 走看看