gpt4 book ai didi

java - 如何实例化封装对象?

转载 作者:行者123 更新时间:2023-12-02 01:39:35 24 4
gpt4 key购买 nike

我目前正在使用 spring。我创建了一个restClient,它使用基于另一个模块的服务。我正在尝试实例化此restClient,但总是收到空指针异常。经过调查,似乎封装的属性(对象)没有实例化,它们的嵌套也没有封装。

这是成员变量、我的类、构造函数和我尝试调用的方法。

private OAuth2RestTemplate oAuth2RestTemplate;
private ConsumedDestinationModel consumedDestinationModel;
@Autowired
private DestinationService<ConsumedDestinationModel> destinationService ;

public DefaultSacRestClient()
{
consumedDestinationModel = getSacConsumedDestinationModel(getDestinationService().getAllConsumedDestinations());
oAuth2RestTemplate = configureOAuth2Credentials(getConsumedDestinationModel());
}


@Override
public List<Story> fetchStories() {
List<Story> stories = new ArrayList<>();

String endpoint = getConsumedDestinationModel().getUrl() + STORIES_URL;

stories.add(oAuth2RestTemplate.getForObject(endpoint, Story.class));
return stories;
}

在我的构造函数中,两种方法 getSacConsumedDestinationModel() &configureOAuth2Credentials() 返回一个对象。

但是方法 getSacConsumedDestinationModel() 使用未实例化的destinationService。我不明白为什么destinationService成员变量没有实例化。

这是仅与我正在处理的模块相对应的应用程序上下文。此应用程序上下文附加到应用程序的全局应用程序上下文

<bean id="defaultSacRestClient" class="de.hybris.platform.sacintegrationbackoffice.client.impl.DefaultSacRestClient">
<property name="destinationService" ref="destinationService"/>
</bean>

<bean id="destinationService" class="de.hybris.platform.apiregistryservices.services.impl.DefaultDestinationService">
<property name="destinationDao" ref="destinationDao"/>
</bean>
<bean id="destinationDao" class="de.hybris.platform.apiregistryservices.dao.impl.DefaultDestinationDao">
<property name="flexibleSearchService" ref="defaultFlexibleSearchService"/>
<property name="modelService" ref="defaultModelService"/>
</bean>

是否是bean配置问题?我错过了什么吗?我肯定做错了什么。

最佳答案

两个可能的问题:

  1. 该类是否用 @Component@Service 注释?
  2. 有些对象是使用构造函数实例化的,有些则不是。

尝试

@Service
public class DefaultSacRestClient {
private final OAuth2RestTemplate oAuth2RestTemplate;
private final ConsumedDestinationModel consumedDestinationModel;
private final DestinationService<ConsumedDestinationModel> destinationService ;

public DefaultSacRestClient(DestinationService<ConsumedDestinationModel> destinationService) {
this.destinationService = destinationService;
this.consumedDestinationModel = getSacConsumedDestinationModel(destinationService.getAllConsumedDestinations());
this.oAuth2RestTemplate = configureOAuth2Credentials(getConsumedDestinationModel());
}
...
}

关于java - 如何实例化封装对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57496847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com