I have a Spring Boot application ( created in http://start.spring.io -JDK8, Spring Boot 2.6.6 ). I am able to build it and start it.
I added a dependency to the existing library :
<dependency>
<groupId>com.connect_responsibilitymgr_services</groupId>
<artifactId>connect-responsibilitymgr-services</artifactId>
<version>1.0.0</version>
</dependency>
In my implementation I got an instance of the class defined in the dependent library :
ToolkitApi toolkitApi = new ToolkitApi();
UserProfile profile = toolkitApi.getUserProfile("123456");
I am getting a NullPointerException inside the implementation of "getUserProfile":
public UserProfile getUserProfile(String id) throws Exception {
try {
HttpHeaders headers = new HttpHeaders();
headers.set("toolkit-token",
CryptoUtils.decrypt(**toolkitConfiguration**.getClientToken(), **toolkitConfiguration**.getEncryptedKey()));
where "toolkitConfiguration" is not instantiated. It's NULL;
In ToolkitApi implementation Bean is being Autowired :
@Controller
public class ToolkitApi {
private static final Logger log = LoggerFactory.getLogger(ToolkitApi.class);
@Autowired
private GISToolConfiguration.ToolkitConfigInfo toolkitConfiguration;
....
@Bean
@ConfigurationProperties("toolkit")
ToolkitConfigInfo toolkitConfigInfo() {
return new ToolkitConfigInfo();
}
public static class ToolkitConfigInfo {
private String hostname;
private String port;
private String clientToken;
private String encryptedKey;
all the properties of the ToolkitConfigInfo are defined in "application.properties" and I am able read them. So my "GISToolConfiguration.ToolkitConfigInfo toolkitConfiguration" is never getting instantiated. I am new to Spring Boot and to me it looks like a Bean in dependent library is not getting instantiated for whatever reason. What could be a problem?
CodePudding user response:
You are instantiating your toolkitApi
with new
:
ToolkitApi toolkitApi = new ToolkitApi();
There Spring DI cannot inject the toolkitConfiguration
. Let Spring inject you that toolkitApi
where you use it.