0

I'm trying to Inject a class to another class and during the post construct the injected class works as expected and when I try to use that class in other methods it throws a null pointer.

If you see the below code, in my Service class I see the postconstruct method is printing the expected value from the map. but the sayhello method would throw a NPE.

What is wrong in the below (the code wont compile ... just wanted to put that on a high level)

@RestController
@Produces(MediaType.APPLICATION_JSON)
@RefreshScope
public class ServRes{

@Inject
ServiceFact service;

@RequestMapping("/test")
public Response helloWorld(){
Service myservice = service.getService();
myservice.sayHello();
}

My ServiceFact

@Named
public class ServiceFact{

public Service getService(){
return new Service();
}

My ServiceClass

@Named
public class Service{

private HashMap dict;

@Inject
Private DictLoader dicLoader

@PostConstruct
public void load(){
this.dict = dicLoader.getDict();
dict.get("1"); // prints 12212
}

public void sayHello(){
System.out.print(dict.get("1")); //throws NPE
}

}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Jeeppp
  • 1,553
  • 3
  • 17
  • 39

1 Answers1

0

The problem is with the

 @Named
public class ServiceFact{

public Service getService(){
return new Service();
}

You are creating a NEW object and not using the spring bean. Consider to refactor the factory to use the created spring bean (Inject).

shippi
  • 2,344
  • 7
  • 22
  • 28