解决方案 »

  1.   

    既然用了Spring了,怎么没用Spring的bean方式来获取对象?
    BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
    "applicationContext.xml"));
    DataSource dataSource = beanFactory.getBean("dataSource", DataSource.class);
    System.out.println(dataSource);
      

  2.   

    你的测试类没有加载spring,怎么能拿到spring 管理的bean?
      

  3.   


    谢谢,刚测试了下,用这个方法的确可以获得dataSource,看来也不是配置文件的问题了。如果纠结再问下,为什么使用上面注入的方式就不能获取,问题出现在哪呢?
      

  4.   


    刚接触spring,你说的具体怎么弄?
      

  5.   


    其实刚开始配置文件里面是没有下面这段代码的:<bean id="dataBean" class="com.memo.dao.ConnectionFactory">  
            <property name="dataSource">  
                <ref bean="dataSource"/>  
            </property>  
        </bean>  
    测试类中是这样子:@Autowired
    DataSource dataSource;  

    public void query()throws Exception{
    log.info("dataSource:"+dataSource);
    Connection conn = dataSource.getConnection();
    System.out.println("conn:"+conn);
    }
    public static void main(String[] args) throws Exception{
    new ConnectionFactory().query();
    }
    使用自动注入的方式,单获得的datasource为null。
      

  6.   

    你上面的代码有注入的方式吗?并不是有了set和get方法就叫注入的。你写的代码和Spring就一点联系都没有,Spring就是用BeanFactory来管理bean的。你可以用:
    beanFactory..getBean("dataBean", ConnectionFactory.class);
    来获取ConnectionFactory的对象,这样它的dataSource属性就自动注入到了。
      

  7.   


    一定使用beanfactory才能获得实例吗,@Autowired
    DataSource dataSource;作用呢?楼主小白,多谢指导。
    在web.xml的中配置:(注:上面的测试类,应该是通过web请求之后才会请求数据库链接)
    <servlet>
    <servlet-name>dispatch</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath*:/config/applicationContext-*.xml</param-value>  
         </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>dispatch</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping>
      

  8.   

    @Autowired似乎是可以省略applicationContext.xml中的bean的property配置,不用配置各个bean的属性了。
    web.xml中的东西似乎是SpringMVC的东西,和创建bean没有关系。
      

  9.   

    你得从spring容器中取得bean,这样DataSource 才会被注入呀!