Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowire Jdbc template

I am trying to auto-wire JDBC template and I'm getting a null pointer exception (template is null). What could be the problem?

@Autowired
template JdbcTemplate;

This is my application context 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>
like image 367
Amit Avatar asked Sep 27 '13 16:09

Amit


People also ask

Can we use JdbcTemplate in spring boot?

Spring Boot supports H2 (an in-memory relational database engine) and automatically creates a connection. Because we use spring-jdbc , Spring Boot automatically creates a JdbcTemplate . The @Autowired JdbcTemplate field automatically loads it and makes it available.

What is JDBC template?

JdbcTemplate is a central class in the JDBC core package that simplifies the use of JDBC and helps to avoid common errors. It internally uses JDBC API and eliminates a lot of problems with JDBC API.

Can we use @autowired for interface?

If you try to use @Autowired on an interface, the Spring framework would throw an exception as it won't be able to decide which implementation class to use.


2 Answers

Instead of this code:

@Autowired
template JdbcTemplate;

You need:

@Autowired
JdbcTemplate template;
like image 178
MariemJab Avatar answered Oct 04 '22 01:10

MariemJab


  1. The bean you try to inject in is not in the spring context;
  2. No setter for the JdbcTemplate
  3. You try to use the template in the constructor before the template is injeted
like image 39
Evgeni Dimitrov Avatar answered Oct 04 '22 01:10

Evgeni Dimitrov