骡子:在spring bean上设置属性

时间:2015-07-09 11:44:43

标签: java spring mule

我使用的是Mule v3.5.0

目前我有一个名为flowContextEnricher的bean,它将对象设置为包含有关流的一些信息的eventContext会话。此信息稍后用于审计日志记录:

@Component
public abstract class AbstractContextEnricher implements Callable {

public Stream buildStream() {
    final Stream stream = ...
    return stream;
}

@Override
public Object onCall(MuleEventContext eventContext) throws Exception {

    final Stream stream = buildStream();

    eventContext.getSession().setProperty("stream", stream);

    return eventContext.getMessage().getPayloadAsString();
}

我想将这个ContextEnricher重用于在线服务和模拟服务,但对于模拟服务,必须将另一个布尔值的模拟设置为“TRUE”。

我可以通过添加一个单独的浓缩器来实现:MockContectEnricher:

@Component
public class MockContextEnricher implements Callable {

    @Override
    public Object onCall(MuleEventContext eventContext) throws Exception {
        eventContext.getSession().setProperty("mock", Boolean.TRUE);
        return eventContext.getMessage().getPayloadAsString();
    }
}

然后我必须为所有模拟流程调用附加组件。我的总流量如下:

<flow name="xxxFlowMock" processingStrategy="synchronous">
    <servlet:inbound-endpoint path="/xxx/mock" responseTimeout="10000" />
    <component>
        <spring-object bean="mockContextEnricher"/>
    </component>
    <component>
        <spring-object bean="xxxContextEnricher"/>
    </component>
    <component>
        <spring-object bean="auditLogger"/>
    </component>
    ...
</flow>

这很有效,但看起来有点奇怪。是不是可以将xxxContextEnricher重用于在线服务和模拟服务,只需在bean上设置一个属性?

<property name="mock" value="true">

实现此目标的最佳方式是什么?

2 个答案:

答案 0 :(得分:1)

拥有另一个MockContextEnricher不应该太糟糕。虽然我认为如果MockContextEnricher类只扩展xxxContextEnricher,你可以做得更好。通过这种方式,你可以这样。

@Component
public class MockContextEnricher extends xxxContextEnricher {

    @Override
    public Object onCall(MuleEventContext eventContext) throws Exception {
        eventContext.getSession().setProperty("mock", Boolean.TRUE);
        return super.onCall(eventContext);
    }
}

或者,如果您想真正删除MockContextEnricher。试试这个。

xxxContextEnricher课程中添加字段(可能是布尔类型),以便&#39;模拟&#39;属性,添加使用它有条件地添加&#39; mock&#39;会话属性。

示例初始化:

<spring:bean id="mockContextEnricher" name="mockContextEnricher" class="com.example.xxxContextEnricher">
   <spring:property name="mock" value="true"/>
</spring:bean>
...
<flow name="xxxFlowMock" processingStrategy="synchronous">
    <servlet:inbound-endpoint path="/xxx/mock" responseTimeout="10000" />
    <component>
        <spring-object bean="mockContextEnricher"/>
    </component>
    <component>
        <spring-object bean="auditLogger"/>
    </component>
    ...
</flow>

答案 1 :(得分:0)

现在我通过向每个模拟流添加一个message-properties-transformer组件来解决它。默认情况下,如果没有指定,我将其设置为false,仅在模拟流程中将属性设置为true。

<message-properties-transformer scope="session">
        <add-message-property key="mock" value="true"/>
</message-properties-transformer>

尽管通过spring-bean对象设置它仍然会更清晰......