如何将ReactiveClientRegistrationRepository参数注入到Spring函数式Bean中?
Absolutely, this is totally feasible! You can absolutely inject the ReactiveClientRegistrationRepository into your functional bean—Spring’s ApplicationContext gives you all the tools you need to pull in existing registered beans when defining new ones programmatically.
Here’s the straightforward way to implement this:
Step 1: Access the Bean from the ApplicationContext
Since the context instance you’re using to register the bean is an ApplicationContext (which extends BeanFactory), you can directly fetch the ReactiveClientRegistrationRepository bean inside your supplier lambda.
Example Code
// Assuming your BeanClass has a constructor that accepts ReactiveClientRegistrationRepository context.registerBean("beanName", BeanClass.class, () -> { // Fetch the already registered ReactiveClientRegistrationRepository bean ReactiveClientRegistrationRepository clientRegistrations = context.getBean(ReactiveClientRegistrationRepository.class); // Pass it to your BeanClass constructor return new BeanClass(clientRegistrations); });
Step 2: Ensure the Dependency is Available
Just make sure that the ReactiveClientRegistrationRepository has already been registered in the context before you try to fetch it. If you’re using Spring Boot’s OAuth2 client auto-configuration (via the spring-boot-starter-oauth2-client starter), this bean is automatically created for you, so you won’t have to manually register it.
Example BeanClass
For clarity, here’s what your BeanClass might look like:
public class BeanClass { private final ReactiveClientRegistrationRepository clientRegistrations; // Constructor injection (the preferred way in Spring) public BeanClass(ReactiveClientRegistrationRepository clientRegistrations) { this.clientRegistrations = clientRegistrations; } // Add your business logic methods here }
Why This Works
The ApplicationContext acts as a central registry for all beans. When you call context.getBean(), Spring looks up the existing bean instance (or creates it if it hasn’t been initialized yet) and returns it. Since your supplier lambda runs during bean registration/initialization, this is a valid way to resolve dependencies for functional beans.
If you run into any issues (like a NoSuchBeanDefinitionException), double-check that you’ve included the necessary OAuth2 client dependencies and that your configuration is set up correctly to enable the auto-registration of ReactiveClientRegistrationRepository.
内容的提问来源于stack exchange,提问作者Christian

