gpt4 book ai didi

java - 如果可能的话,是否可以在请求范围内注入(inject)bean,如果它对于线程不活跃,则注入(inject)原型(prototype)?

转载 作者:行者123 更新时间:2023-12-01 22:40:40 24 4
gpt4 key购买 nike

我想将请求作用域 bean 注入(inject)到单例作用域中。我可以使用Provider来做到这一点。当没有范围请求对线程不活动时,就会出现此问题。在这种情况下,我想将 bean 注入(inject)例如原型(prototype)范围。那可能吗?例如。代码:

public class Tenant {

private String name;

...
}
@Configuration
public class AppConfig {

@Bean
@Scope(ConfigurableBeanFactory.SCOPE_REQUEST)
public Tenant prototypeBean() {
return new Tenant();
}

@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Tenant prototypeBean() {
return new Tenant();
}

@Bean
public MySingletonBean singletonBean() {
return new MySingletonBean();
}
public class MySingletonBean {

@Autowired
private Provider<Tenant> beanProvider;
//inject conditionally on request or prototype scope

public void showMessage() {
Tenant bean = beanProvider.get();
}
}

我想避免此消息出现错误:

Error creating bean with name 'tenantDetails': 
Scope 'request' is not active for the current thread;
consider defining a scoped proxy for this bean if you intend to
refer to it from a singleton;
nested exception is java.lang.IllegalStateException: No thread-bound
request found: Are you referring to request attributes outside of an
actual web request, or processing a request outside of the originally
receiving thread? If you are actually operating within a web request
and still receive this message, your code is probably running outside
of DispatcherServlet/DispatcherPortlet: In this case, use
RequestContextListener or RequestContextFilter to expose the current
request.

最佳答案

如果需要类似的东西,那么应该重新考虑应用程序的设计。

这可能吗?是的。

@Component
@RequestScope
public class RequestScopeTenant implements Tenant {

private String name;

...
}

这样我们就有了请求作用域的 bean。

@Component
@PrototypeScope
public class DefaultTenant implements Tenant {

private String name;

...
}

这里我们有默认的租户。

@Configuration
public class AppConfig {

@Primary
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Tenant prototypeBean(RequestScopeTenant requestScopeTenant, DefaultTenant defaultTenant) {
return RequestContextHolder.getRequestAttributes() != null ? requestScopeTenant : defaultTenant;
}

@Bean
public MySingletonBean singletonBean() {
return new MySingletonBean();
}

这样,当没有可用的请求范围时,将返回默认租户。

再说一次,如果您必须实现类似的东西 - 更改设计或创建自定义范围。

关于java - 如果可能的话,是否可以在请求范围内注入(inject)bean,如果它对于线程不活跃,则注入(inject)原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58499219/

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