小编典典

将请求范围的bean注入另一个bean

spring-boot

我想创建一个在请求生命周期中唯一的UUID。为此,我创建了一个带有@Scope(“ request”)批注的UUID bean。

@Bean
@Scope(scopeName = WebApplicationContext.SCOPE_REQUEST)
public UUID requestUUID() {
    return UUID.randomUUID();
}

我想在控制器中访问此bean。所以我用@Autowired注入了它。这很好。

@Controller
public class DashboardController {

    @Autowired
    UUID uuid;

    @Autowired
    WelcomeMessageService welcomeMessageService;

    @Autowired
    IssueNotificationService issueNotificationService;

    @RequestMapping("/")
    public String index(Model model) throws InterruptedException, ExecutionException {
        System.out.println(uuid);
        PortalUserDetails userLog = getPortalUserDetails();

        BusinessObjectCollection<WelcomeMessage> welcomeMessages = welcomeMessageService.findWelcomeMessages(
                20,
                0,
                userLog.getZenithUser(),
                userLog.getConnectionGroup().getConnectionGroupCode(),
                "FR");
        if(welcomeMessages!=null) {
            model.addAttribute("welcomeMessages", welcomeMessages.getItems());
        }

        BusinessObjectCollection<IssueNotification> issueNotifications =
                issueNotificationService.findIssueNotifications(userLog.getZenithUser());

        if(welcomeMessages!=null) {
            model.addAttribute("welcomeMessages", welcomeMessages.getItems());
        }
        model.addAttribute("issueNotifications", issueNotifications);

        return "index";
    }
}

控制器调用多个服务。每个服务都使用RestTemplate bean。在这个RestTemplate bean中,我想获取UUID。

@Component
public class ZenithRestTemplate extends RestTemplate {   
    @Autowired
    private UUID uuid;

    public void buildRestTemplate() {
        List restTemplateInterceptors = new ArrayList();
        restTemplateInterceptors.add(new HeaderHttpRequestInterceptor("UUID", uuid.toString()));
        this.setInterceptors(restTemplateInterceptors);
    }
}

当我尝试在此处注入UUID时,出现错误:

创建名称为“
zenithRestTemplate”的bean时出错:自动连接依赖项的注入失败;嵌套的异常是org.springframework.beans.factory.BeanCreationException:无法自动连线字段:私有java.util.UUID
com.geodis.rt.zenith.framework.webui.service.ZenithRestTemplate.uuid;
嵌套的异常是org.springframework.beans.factory.BeanCreationException:创建名称为’requestUUID’的bean时出错:当前线程的作用域’request’无效;如果您打算从单例中引用它,请考虑为此bean定义作用域代理。嵌套异常为java.lang.IllegalStateException:找不到线程绑定的请求:您是在实际的Web请求之外引用请求属性,或在原始接收线程之外处理请求?如果您实际上是在Web请求中操作并且仍然收到此消息,则您的代码可能在DispatcherServlet
/
DispatcherPortlet之外运行:在这种情况下,请使用RequestContextListener或RequestContextFilter公开当前请求。

如何在RestTemplate bean中访问我的UUID bean?

我的项目使用Spring-MVC,带有Java配置的Spring-boot。

我已经尝试添加一个RequestContextListener,但是不能解决问题。

@Bean public RequestContextListener requestContextListener(){
    return new RequestContextListener();
}

阅读 488

收藏
2020-05-30

共1个答案

小编典典

我认为您需要将UUID请求范围的bean 标记为:

@Scope(scopeName = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)

如果控制器是singleton作用域bean,request则要在其中注入作用域bean。由于单例bean在其生命周期内仅注入一次,因此您需要提供作用域Bean作为代理来解决此问题。

另一种选择是改为使用org.springframework.web.context.annotation.RequestScope注释:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Scope(WebApplicationContext.SCOPE_REQUEST)
public @interface RequestScope {

    @AliasFor(annotation = Scope.class)
    ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;

}

@RequestScope是关于以下内容的元注释@Scope:1)将scopeto 设置为"request"2)将proxyModeto
设置为,ScopedProxyMode.TARGET_CLASS因此您不必每次都想定义请求范围的bean时就这样做。

编辑:

请注意,您可能需要添加@EnableAspectJAutoProxy主配置类。

2020-05-30