spring - Spring IoC:每个请求的标识符
问题描述
我创建了这个 bean 以获得Supplier<String>
:
@Bean
public Supplier<String> auditIdSupplier() {
return () -> String.join(
"-",
"KEY",
UUID.randomUUID().toString()
);
}
如您所见,它旨在仅生成一个简单的标识符字符串。
每次调用它时,都会提供一个新的标识符。
我想更改此行为,以便在请求范围内获得相同的生成标识符。我的意思是,第一次达到请求时,会生成一个新的标识符。从那时起, next 调用 no thisSupplier
必须返回请求范围内的第一个生成的标识符。
有任何想法吗?
解决方案
您需要配置一个请求范围的bean
@Configuration
public class MyConfig {
@Bean
@RequestScope
public String myRequestScopedIdentifyer(NativeWebRequest httpRequest) {
// You don't need request as parameter here, but you can inject it this way if you need request context
return String.join(
"-",
"KEY",
UUID.randomUUID().toString());
}
然后在适当的地方使用任一现场注入注入它
@Component
public class MyClass {
@Autowired
@Qualifier("myRequestScopedIdentifyer")
private String identifier
或对象工厂
@Component
public class MyClass {
public MyClass(@Qualifier("myRequestScopedIdentifyer") ObjectFactory<String> identifyerProvider) {
this.identifyerProvider= identifyerProvider;
}
private final ObjectFactory<String> identifyerProvider;
public void someMethod() {
String requestScopedId = identifyerProvider.getObject();
}
推荐阅读
- c# - MagickNET - 比较两张图片并仅显示差异,其余透明
- amazon-web-services - 将文件列表从 s3 存储桶复制到另一个
- python - 更改标签大小 - 足球场
- .net - dotnet-dump 不在 macOS 上创建文件
- javascript - 引导折叠/展开具有不同折叠状态的多个目标
- angular - angular - 如何翻译用户输入的文本(在开发过程中未指定)
- javascript - 应打印从键盘输入的文本的自定义事件
- vue.js - Vue CLI:只为异步 Web 组件捆绑公共依赖项一次
- jquery - 数据表在行中隐藏/显示类
- javascript - 擦除()函数完成时如何执行类型()函数