@Component
@Configuration
public class PartnerService {
private PartnerData partnerData = new PartnerData();
public void setPartnerData(PartnerData partnerData) {
this.partnerData = partnerData;
}
public PartnerData getPartnerData() {
return partnerData;
}
@ConfigurationProperties("partner.cred")
public static class PartnerData {
private Map<String, PartnerCredential> data = new HashMap<>();
public Map<String, PartnerCredential> getData() {
return data;
}
public void setData(Map<String, PartnerCredential> data) {
this.data = data;
}
}
public class PartnerCredential {
private String clientId;
private String clientSecret;
public PartnerCredential() {
}
public String getClientId() {
return clientId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
}
I have to set the value in the application property
partner.cred.data={\
key: {clientId : 'id', clientSecret : 'secret'}\
}
Map.get("key") is throwing NPE the return value of "java.util.Map.get(Object)" is null.
Please don't downvote, I saw and tried to implement suggestion to similar questions, but I am not sure what is wrong, I am guessing the syntax is wrong in the property file but I am not sure what.
CodePudding user response:
set your application.property file like this:
partner:
cred:
data:
key:
clientId : id
clientSecret : secret
CodePudding user response:
My guess is that the nullpointer-issue is due to the fact that your service is not aware of PartnerData.
To solve this problem (and avoid circular dependency):
- Extract
PartnerData
in a separate configuration-class - Wire
PartnerData
in the service, preferably via constructor injection - Insert PartnerData in your
application.properties
This should look something like:
Configuration properties
@Configuration
@ConfigurationProperties(prefix = "partner.cred")
public class PartnerData {
private Map<String, PartnerCredential> data = new HashMap<>();
public Map<String, PartnerCredential> getData() {
return data;
}
public static class PartnerCredential {
private String clientId;
private String clientSecret;
//getters and setters
...
}
}
The Service
@Configuration
class PartnerService {
private final PartnerData partnerData;
// constructor injection
public PartnerService(PartnerData partnerData) {
this.partnerData = partnerData;
}
public PartnerData getPartnerData() {
return partnerData;
}
}
application.properties where one
and two
are the keys of the map
partner.cred.data.one.clientId=1
partner.cred.data.one.clientSecret=secret_1
partner.cred.data.two.clientId=2
partner.cred.data.two.clientSecret=secret_2