gpt4 book ai didi

java - 访问外部库构造对象中的 Spring 应用程序上下文

转载 作者:行者123 更新时间:2023-12-01 17:19:23 25 4
gpt4 key购买 nike

我正在使用 Spring Kafka 库,我想创建可以访问 ApplicationContext 的拦截器。但是,该库为我创建对象并且不注入(inject)依赖项。

@Component
public class ExampleProducerInterceptor extends ProducerInterceptor<Object, Object> {
@Autowired
private Environment environment;
...
}

application.yaml:

spring:
kafka:
properties:
"interceptor.classes": com.example.ExampleproducerInterceptor

Kafka 本身使用此属性通过调用 spring 外部的默认构造函数来构造对象。

有哪些方法可以访问这样的应用程序?例如,我可以向 Kafka 提供一个委托(delegate)类来调用那里的默认构造函数吗?

我已经有一些代码在构建之前配置 kafka,因此我也可以事先修改类名:

@Autowired
private List<ProducerInterceptor> producerInterceptors;

List<String> producerClassNames = producerInterceptors
.map(Object::getClass)
.map(Class::getName)
.map(str -> str + "$enhancedBySpring") // Point to delegate class?
.collect(Collectors.toList());

最佳答案

我不确定你的最后一个代码片段想要实现什么目的。

根据应用程序的复杂性,您可以将 ApplicationContext 存储在静态“holder”类或 ThreadLocal 中,并在第一次调用 时初始化拦截器>send() 或在默认 CTOR 中。

public class ContextHolder {

private static final ApplicationContext context;

...

}

```java
public class ContextHolder {

private final ThreadLocal<ApplicationContext> contexts = new ThreadLocal<>();

...

关于java - 访问外部库构造对象中的 Spring 应用程序上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61325270/

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