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>
  • 相关阅读:
    010editor爆破与注册机
    [FlareOn4]notepad
    [FlareOn6]Snake(NES逆向)
    [FlareOn6]Memecat Battlestation
    [FlareOn6]FlareBear
    回车符和换行符之间的区别
    docker配置搭建elasticsearch集群
    docker部署安装harbor
    ansible的get_url模块
    ansible的lineinfile与blockinfile模块
  • 原文地址:https://www.cnblogs.com/Sorean/p/3023300.html
Copyright © 2011-2022 走看看