5

尝试在 Spring bean 的 init 方法中将消息发布到通道时出现“调度程序没有订阅者”错误。请看下面的例子:

应用程序上下文.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:rmi="http://www.springframework.org/schema/integration/rmi"
    xmlns:int="http://www.springframework.org/schema/integration"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration
        http://www.springframework.org/schema/integration/spring-integration.xsd
        http://www.springframework.org/schema/integration/rmi
        http://www.springframework.org/schema/integration/rmi/spring-integration-rmi.xsd">

    <bean id="currencyService" class="com.demo.CurrencyService" init-method="init"/>

    <int:channel id="currencyChannel" />
    <int:channel id="currencyReplyChannel">
        <int:queue/>
    </int:channel>
    <rmi:outbound-gateway id="currencyServiceGateway"
        request-channel="currencyChannel" remote-channel="currencyServiceChannel"
        reply-channel="currencyReplyChannel" host="localhost" port="2197" />
</beans>

Spring托管bean:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.core.MessagingTemplate;
import org.springframework.integration.core.PollableChannel;
import org.springframework.integration.message.GenericMessage;

public class CurrencyService {

    @Autowired
    private MessageChannel currencyChannel;

    @Autowired
    private PollableChannel currencyReplyChannel;

    private CurrencyListBO currencyListBO;

    public CurrencyListBO getCurrencyList() {
        return currencyListBO;
    }

    public void init() {
        CurrencyIN request = new CurrencyIN();
        request.setChannelCode("RMW");
        request.setTransactionType(CurrencyIN.TransactionType.currencyLoaderService
                .toString());
        GenericMessage<IRequestBO> message = new GenericMessage<IRequestBO>(
                request);
        MessagingTemplate template = new MessagingTemplate();
        template.send(currencyChannel, message);
        Message<CurrencyListBO> reply = template.receive(currencyReplyChannel);
        currencyListBO = reply.getPayload();
    }
}

如果不是 init 方法,而是在第一次调用之后初始化 currencyListBO,那么一切正常。

public CurrencyListBO getCurrencyList() {
    if(currencyListBO == null) {
        init();
    }
    return currencyListBO;
}

请让我知道第一种方法有什么问题。

4

1 回答 1

7

init/@PostConstruct 方法在你的 bean 被实例化之后但在上下文的其余部分被连接之前调用(在这种情况下,在 RMI 适配器订阅通道之前)。

您需要等到上下文完全刷新。

一种方法是实施

ApplicationListener<ContextRefreshedEvent>

并将您的代码放入

public void onApplicationEvent(ContextRefreshedEvent event)

该方法将在上下文完全连接后调用。

于 2012-06-21T11:49:11.637 回答