1

When i call a service layer from controller,data are being saved in database.

My controller is:

@RestController
@RequestMapping("/api")
public class ApiController {
    @Autowired(required = true)
    PersonService personService;        //This is service layer class

    @RequestMapping("/add")
    public void add(){

        person.setLastName("Rahim");
        person.setFirstName("Uddin");
        person.setAddress("Dhaka");
        person.setCity("Dhaka");
        personService.add(person);
   }
}

Service layer is:

@Service
@Transactional
public class PersonServiceImpl implements PersonService {
    @Autowired
    PersonDao personDao;
    @Override
    public void addPerson(Person person) {

        personDao.addPerson(person);

    }
}

Till now everything is ok.

But when i call the service layer through another class, null pointer exception is being shown. At that time: My controller is:

@RestController
@RequestMapping("/api")
public class ApiController {
    @Autowired(required = true)
    PersonService personService;        //This is service layer class

    @RequestMapping("/add")
    public void add(){

          MiddleClass m=new MiddleClass();
          m.create();
   }
}

My MiddleClass is:

public class MiddleClass {
    @Autowired
    PersonService personService;    
    public void create(){


        Person person=new Person();
        person.setLastName("Rahim");
        person.setFirstName("Uddin");
        person.setAddress("Dhaka");
        person.setCity("Dhaka");


        personService.addPerson(person);//this time same service layer 
                                 //is showing null pointer exception here

    }
}

WHY?????????? is it for lacking of any annotation in MiddleClass?

Ishmam Shahriar
  • 51
  • 3
  • 10
  • Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Mark Rotteveel Feb 21 '16 at 09:12

1 Answers1

1

You're creating the MiddleClass instance yourself, using new. So Spring has no way to know that it has to inject the service into the MiddleClass instance. It can only inject beans into other beans it creates itself.

So, MiddleClass must be a Spring bean, and it must be autowired into the controller, just like the service is.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255