RequestScoped bean被注入到HandlerFunction中

时间:2018-10-29 04:05:53

标签: java spring spring-webflux

下面是到webflux HandlerFunction的Route配置。我正在使用Spring Cloud Config来获取属性。这里,我有一个动态属性originairports.shutdown,该属性在属性文件中经常更改,每当我向服务提供String airports http POST时,就会使用@Value("${originairports.shutdown}") String airports将其注入/actuator/bus-refresh变量中。为此,我给了注释@RefreshScope。然后,我将逗号分隔的String转换为List并将其注册为请求范围的Bean,因为当值动态更改时我想要一个新的Bean。

@Configuration
@RefreshScope
public class SearchRoutes
{   
    @Value("${originairports.shutdown}")
    String airports;

    @Bean
    @Scope(scopeName = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public List<String> originAirports()
    {
        logger.info("Origin Airports in shutdown " + airports);
        return Arrays.asList(airports.split(","));
    }  

@Bean
    RouterFunction<ServerResponse> search()
    {
        RouterFunction<ServerResponse> searchRoutes = RouterFunctions.route(POST("/search/get"),
                                                                            searchHandler.search);
        return searchRoutes;

    }  
}

下面是Handler类代码,其中我@Autowire Bean检查该值以相应地返回响应。该应用程序完美启动,但是当我发出请求时,出现错误java.lang.IllegalStateException: No Scope registered for scope name 'request'。那么这段代码是什么问题呢?

@Component
public class SearchHandler
{
    @Autowired
    private List<String> originAirports;

    public HandlerFunction<ServerResponse> search = request ->
    {
        Mono<SearchQuery> searchQuery = request.bodyToMono(SearchQuery.class);

        return searchQuery.flatMap(sq ->
        {
            if (originAirports.contains(sq.getOrigin()))
            {
                logger.info("The origin airport " + sq.getOrigin() + " is in shutdown state");
                return ServerResponse.notFound()
                        .build();
            }
         }
     }
}

1 个答案:

答案 0 :(得分:0)

也许这是一个愚蠢的问题,但是我花了一些时间才能解决。我刚刚创建了一个新组件,并使用Scope原型使其能够正常工作。这是代码。

@Component
@RefreshScope
@Scope("prototype")
public class RefreshComponent
{
    private static final Logger logger = LoggerFactory.getLogger(RefreshComponent.class);

    @Value("${originairports.shutdown}")
    String airports;

    public String originAirports()
    {
        logger.info("Origin Airports in shutdown " + airports);
        return new String(airports);
    }

}