在 Spring MVC 中创建具有请求范围的 `java.lang.String` 类型的命名 bean

Create a named bean of type `java.lang.String` with request scoping in Spring MVC

我有配置 class SpecialEventsConfig.

我正在尝试初始化一个字符串类型的请求 Scoped bean。


    @Bean("requestTime")
    public String getRequestTime() {
        return String.valueOf(System.nanoTime());
    }

这可行,但它会初始化一个单例。我想用它来为请求范围初始化一个字符串。


    @Bean("requestTime")
    @RequestScope(proxyMode = ScopedProxyMode.TARGET_CLASS)// Tried NO and INTERFACES as well
    public String getRequestTime() {
        return String.valueOf(System.nanoTime());
    }

这可以解决我的问题,但不幸的是它不起作用。


有没有办法实现这种行为?

要使用 bean 的请求范围,您可以使用

@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)

@RequestScope

我想你可以试试这个解决方法。

@Bean("requestTime")
@RequestScope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public Supplier<String> getRequestTime() {
    long time = System.nanoTime();
    return () -> String.valueOf(time);
}