我已经使用spring编写了一个库,用于非spring和基于spring引导的应用程序。
我使用消息网关将集成流公开为普通的旧java接口,供其他类使用
import org.springframework.messaging.Message;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public interface SwiftalkKafkaGateway {
@Async
void publish(Message<?> message);
}
我在通过spring上下文获取这个网关类的示例时遇到了麻烦;使用这个库的一个应用程序运行在javaee8cdi环境中;为此我写了一个像这样的加载器
@Singleton
@ApplicationScoped
public class SwiftalkAnnotatedSpringContextLoader {
private final AnnotationConfigApplicationContext springContext;
SwiftalkAnnotatedSpringContextLoader(String propertiesFile) throws IOException {
springContext = new AnnotationConfigApplicationContext();
ConfigurableEnvironment environment = new StandardEnvironment();
MutablePropertySources propertySources = environment.getPropertySources();
Properties appProps = new Properties();
appProps.load(this.getClass().getClassLoader().getResourceAsStream(propertiesFile));
propertySources.addFirst(new PropertySource<Properties>("spring-properties", appProps) {
@Override
public Object getProperty(String name) {
return appProps.getProperty(name);
}
});
springContext.setEnvironment(environment);
springContext.scan("com.foo.cloud.swiftalk");
springContext.refresh();
}
ApplicationContext getSwiftalkKafkaClientContext() {
return this.springContext;
}
}
但是获取bean示例失败
SwiftalkKafkaGateway kafkaGateway = loader.getSwiftalkKafkaClientContext().getBean(
SwiftalkKafkaGateway.class);
assertNotNull(kafkaGateway);
带着错误
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.foo.cloud.swiftalk.SwiftalkKafkaGateway' available
这是由于
21:37:42.003 [main] DEBUG org.springframework.context.annotation.ClassPathBeanDefinitionScanner - Ignored because not a concrete top-level class: URL [jar:file:/Users/anadimishra/.m2/repository/com/foo/cloud/swiftalk-kafka-client/1.0.0-SNAPSHOT/swiftalk-kafka-client-1.0.0-SNAPSHOT-jar-with-dependencies.jar!/com/foo/cloud/swiftalk/SwiftalkKafkaGateway.class]
如何在非spring环境中获得此服务的示例?
更新
我使用这个的集成流程
@Bean
public IntegrationFlow kafkaPublisherFlow(KafkaProducerMessageHandler<String, String> kafkaProducerMessageHandler,
RequestHandlerRetryAdvice retryAdvice,
ExecutorChannel kafkaPublishChannel) {
return IntegrationFlows.from(SwiftalkKafkaGateway.class)
.channel(kafkaPublishChannel)
.handle(kafkaProducerMessageHandler, e -> e.advice(retryAdvice))
.get();
}
我们的想法是能够在spring-boot和非spring-boot应用程序中重用这个带有错误处理和幂等操作代码的kafka发布服务器。
1条答案
按热度按时间k10s72fa1#
如果你想用sprint boot的
@EnableAutoConfiguration, you should be using
Spring应用or
springapplicationbuilderto create the application context, not creating an
annotationconfigapplicationcontext`。