【问题标题】:How to instantiate encapsulated object?如何实例化封装的对象?
【发布时间】:2019-08-14 14:36:00
【问题描述】:

我目前正在使用弹簧。我创建了一个使用基于另一个模块的服务的 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配置问题?我错过了什么吗?肯定是我做错了什么。

【问题讨论】:

    标签: java spring-boot hybris


    【解决方案1】:

    两个可能的问题:

    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());
        }
        ...
    }
    

    【讨论】:

    • 在调用构造函数之前,bean(成员变量)是否被注入(实例化)?
    • 如果这是一个 bean(注解并在您的组件扫描中),spring 将实例化并注入目标服务。
    猜你喜欢
    • 1970-01-01
    • 2016-08-23
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多