gpt4 book ai didi

java - 如何判断是否需要用@Bean进行注解

转载 作者:行者123 更新时间:2023-12-01 16:28:32 25 4
gpt4 key购买 nike

如何确定在 Spring 集成中,我需要使用 @Bean 进行注释?

例如,让我们看一下 @Transformer 注释。

考虑以下代码片段:

1.

    @AllArgsConstructor
@Getter
@Setter
@ToString
private static class Person {
private String firstName;
private String lastName;
private String phone;
}

@Override
public void run(ApplicationArguments args) {
firstChannel.send(MessageBuilder.withPayload(new Person("s", "f", null)).build());
}

// without bean
@Transformer(inputChannel = FIRST_CHANNEL, outputChannel = SECOND_CHANNEL)
public ContentEnricher contentEnricher() {
ContentEnricher contentEnricher = new ContentEnricher();
contentEnricher.setPropertyExpressions(ImmutableMap.of("phone", new ValueExpression("123")));
return contentEnricher;
}

@ServiceActivator(inputChannel = SECOND_CHANNEL)
private void fromSecondChannel(Message<?> message) {
System.out.println(message.getPayload());
}

2.

    // with bean
@Bean
@Transformer(inputChannel = FIRST_CHANNEL, outputChannel = SECOND_CHANNEL)
public HeaderEnricher headerEnricher() {
return new HeaderEnricher(ImmutableMap.of("key1", new StaticHeaderValueMessageProcessor<>("value1")));
}

没有 @Bean 的代码片段 nr 2 的输出是:

GenericMessage [payload=org.springframework.integration.transformer.HeaderEnricher@15a3b42, headers={id=76d24f2c-8b64-a254-8733-8b5911871cce, timestamp=1590856526985}]

对于 @Bean 来说是:

GenericMessage [payload=DemoApplication11.Person(firstName=s, lastName=f, phone=null), headers={key1=value1, id=55e5b4b7-9a4b-8822-4398-b42755bc7697, timestamp=1590856617667}]

最佳答案

没有 @Bean 意味着转换器被作为 POJO 方法调用。

@Transformer(...)
public String transform(String in) {
return in.toUpperCase();
}

如果转换器实际上是 Transformer 的实现(例如 header 丰富器),则需要 @Bean

ContentEnricher 不是一个转换器,它是一个 MessageHandler,因此必须用 @ServiceActivator@Bean 注解.

参见the documentationhere .

Starting with version 4.0, you can configure messaging annotations on @Bean method definitions in @Configuration classes, to produce message endpoints based on the beans, not the methods. It is useful when @Bean definitions are “out-of-the-box” MessageHandler instances (AggregatingMessageHandler, DefaultMessageSplitter, and others), Transformer instances (JsonToObjectTransformer, ClaimCheckOutTransformer, and others), and MessageSource instances (FileReadingMessageSource, RedisStoreMessageSource, and others). The following example shows how to use messaging annotations with @Bean annotations ...

关于java - 如何判断是否需要用@Bean进行注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62105493/

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