我用spring编写了一个库,用于非spring和Spring应用程序中。
我使用消息传递网关将Integration公开为一个普通的旧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上下文获取这个网关类的实例时遇到了困难;其中一个使用这个库的应用程序运行在JavaEE 8 CDI环境中;为此,我编写了一个如下所示的加载程序
@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();
}这个想法是为了能够重用这个卡夫卡发行者的错误处理和幂等操作代码,在春季引导和非春季引导应用程序。
发布于 2021-04-05 17:03:59
如果您想使用Sprint的SpringApplicationorSpringApplicationBuilderto create the application context, not creating anAnnotationConfigApplicationContext`. @EnableAutoConfiguration, you should be using
https://stackoverflow.com/questions/66956085
复制相似问题