2017-08-28 41 views
0

我正在嘗試將一個類注入到另一個類中,並且在構建過程中注入的類按預期工作,當我嘗試在其他方法中使用該類時,它會引發空指針。只在postConstruct期間彈入加載類

如果您看到下面的代碼,那麼在我的Service類中,我看到postconstruct方法正在從地圖打印預期值。但sayhello方法會拋出NPE。

什麼是錯在下面的(代碼不會編譯...只想把那一個高電平)

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

@Inject 
ServiceFact service; 

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

我ServiceFact

@Named 
public class ServiceFact{ 

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

我的服務類

@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 
} 

} 

回答

0

問題出在

@Named 
public class ServiceFact{ 

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

您正在創建一個NEW對象而不使用spring bean。考慮重構工廠以使用創建的spring bean(Inject)。