0

I am using Spring 4.1.1. I have the following in my spring-dispatcher-servlet.xml

<context:component-scan base-package="com.au.controller,com.au.util" /> 
<mvc:resources location="/" mapping="/**" />
<mvc:annotation-driven />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/caballocation" />
    <property name="username" value="root" />
    <property name="password" value="1234" />
</bean>

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

<bean id="AddImplDao" class="com.au.dao.AddressDaoImpl" />

I have the following controller class in package com.au.controller

  @Controller
  public class ControllerMain {

    @Autowired
    AddressDao obj;
    @RequestMapping(value = "/test")
    public @ResponseBody String test(){
        //logger.debug("getWelcome is executed!");
        obj.select();
        return "1";
    }

}

In the above code obj.select works as it gets autowired.

But the following class which is in com.au.util package have the value null of the object which is autowired.

    public class DistanceCalculator {

        @Autowired
        AddressDao obj1;
        public String calculate(String from, String to) throws IOException, JSONException {
        ..
        Map output = obj1.calc(from, to);
        ..
        }

Obj1 is null while execution. Getting java.lang.NullPointerException at obj1.calc(from,to)

Following is the interface and its implementation. AddressDao.java

public interface AddressDao {
    public void select();
    public Map calc(String from,String to);
}

AddressDaoImpl.java

public class AddressDaoImpl implements AddressDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private SimpleJdbcCall simpleJdbcCall;

    @Autowired
    public void setDataSource(DataSource dataSource) {
       this.simpleJdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("CheckForValuesInDB");
    }

    @Override
    public void select() {
        // TODO Auto-generated method stub
    }

    @Override
    public Map calc(String from, String to) {
        // TODO Auto-generated method stub}

What is the reason behind this?

1 Answers1

-1

you have to add extra space in com.au.controller,com.au.util so it should look like 'com.au.controller, com.au.util'. As for now only com.au.controller is scanned by your configuration.

//Edit There should be @Component annotation in DistanceCalculator class

leonz
  • 133
  • 1
  • 4