【问题标题】:Spring bean partial autowire prototype constructorSpring bean 部分自动装配原型构造函数
【发布时间】:2016-10-25 00:49:54
【问题描述】:

我有一堂课:

@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WebSocketRegistrar extends AbstractWebSocketHandler{


    private final ApplicationContext context;



    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // problem here.
        context.getBean(WebSocketConsumer.class, session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {

    }

}

它尝试创建一个原型 bean,其中 1 个参数是运行时参数,其余的我想注入。我需要它来获取 EventBus 和一个函数。两者都在上下文中可用,我可以解决这个问题。我试图了解如何在原型上进行部分构造函数自动装配

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@NoArgsConstructor
public class WebSocketConsumer implements Consumer<Identifiable<?>> {

    private WebSocketSession session;

    private Function<Identifiable<?>, String> jsonApi;

    @Autowired
    public WebSocketConsumer(WebSocketSession session, EventBus bus, BiFunction<Identifiable<?>, String, String> toJsonApi) {
        this.session = session;
        this.jsonApi = identifiable -> toJsonApi.apply(identifiable,session.getHandshakeHeaders().get("Host").get(0));
        bus.on(R(session.getUri().getPath() + "/?.*"),this::accept);

    }


    @Override
    public void accept(Identifiable<?> update) {

    }

}

【问题讨论】:

    标签: java spring


    【解决方案1】:

    我认为您可能需要重新表述您的问题,或者问一个关于您希望在 Spring 中实现什么的非常简单的示例,或者只是询问您遇到的纯 Spring DI 问题。但无论如何,在 Spring Dependency Injection 方面,听起来您需要的是一个配置,您可以从中创建 bean:

    @Configuration
    public class TestConfiguration {
    
        @Bean
        @Autowired
        @Scope("prototype")
         public SomePrototypeBean createBean(SingletonBean singletonBean){
              return new SomePrototypeBean(singletonBean, "TODO whatever you want here" );
         }
    }
    

    通过这种方式,您可以更好地控制进入 bean 的构造函数参数,并且可以在构造函数中放入单例 bean,以及在运行时更改的某种参数,我将其保留为 TODO。不惜一切代价避免context.getBean。如果您发现自己在做这些事情,您可能需要重新考虑您尝试实现某事的方式。它只能用于克服框架的限制,如果存在任何其他解决方案,则更可取。

    【讨论】:

    • 很抱歉,在配置中自动装配 bean 可能不是最好的主意,这篇文章详细介绍了要做什么stackoverflow.com/questions/28747743/…
    • 我已经编辑了我的答案,现在应该这样做。
    猜你喜欢
    • 2017-08-16
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 2016-08-17
    • 2013-01-29
    • 1970-01-01
    相关资源
    最近更新 更多