【问题标题】:Autowire Jdbc template自动装配 Jdbc 模板
【发布时间】:2013-09-27 16:56:26
【问题描述】:

我正在尝试自动连接 JDBC 模板,但出现空指针异常(模板为空)。可能是什么问题呢?

@Autowired
template JdbcTemplate;

这是我的应用程序上下文 xml:

<bean ..>
    <mvc:annotation-driven />

            <context:component-scan base-package="igate.dto" />
                <context:component-scan base-package="igate.dao" />
                    <context:component-scan base-package="igate.service" />
                        <context:component-scan base-package="igate.controller" />
                <context:component-scan base-package="igate.logs" />
                    <context:component-scan base-package="igate.testcases" />


    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="prefix" value="/"/>
          <property name="suffix" value=".jsp" />
            </bean> 


    <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@172.21.17.5:1521:oraten" />
        <property name="username" value="lab01trg21" />
        <property name="password" value="lab01oracle" />
    </bean>

    <bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="ds"/>
    </bean>

</beans>

【问题讨论】:

  • 开始你不需要 6 个&lt;component-scan&gt; 元素。您只需要一个逗号分隔值:&lt;context:component-scan base-package="igate.dto, igate.dao, igate.service, ..." /&gt;
  • 此 xml 配置是调度程序 servlet 上下文 xml 配置还是根应用程序上下文初始化程序 xml 配置?请记住,如果第一个为真,则您无法从根 webapp 上下文应用服务中引用 jdbc 模板。

标签: spring spring-mvc jdbctemplate


【解决方案1】:

代替这段代码:

@Autowired
template JdbcTemplate;

你需要:

@Autowired
JdbcTemplate template;

【讨论】:

    【解决方案2】:
    1. 您尝试注入的 bean 不在 spring 上下文中;
    2. JdbcTemplate 没有设置器
    3. 您尝试在模板注入之前在构造函数中使用模板

    【讨论】:

      【解决方案3】:

      此错误的一个原因是混合了自动装配和手动装配 创建 bean。

      例如,您有一个自动装配 bean 的服务类。

      @Service
      public class CarService {
      
          @Autowired
          public JdbcTemplate jdbcTemplate;
      
          // service code
      }
      

      但后来没有

      @Autowired
      private CarService carService;
      

      你会的:

      CarService carService = new CarService();
      

      【讨论】:

        猜你喜欢
        • 2015-02-26
        • 1970-01-01
        • 2018-05-04
        • 1970-01-01
        • 1970-01-01
        • 2011-12-12
        • 2012-01-04
        • 2012-12-15
        • 1970-01-01
        相关资源
        最近更新 更多