Injecting dependency to a Spring bean

2019-09-15 01:28发布

I would like to inject a singleton object dependency to a Spring bean. The catch is that I can't access and modify the class whose object I want to be injected. Let me describe on the example.

So I have my interface, and the implementation of this interface, like the following.

public interface MyServiceProxy {

    String BEAN_NAME = "MyServiceProxy";

    Data getData(String dataId);
}


public class MyServiceProxyImpl implements MyServiceProxy {

    private final MyServiceClient client;

    public MyServiceProxyImpl(MyServiceClient client) {
        this.client = client;
    }

    @Override
    public Data getData(String dataId) {//...}

Then in my Configuration class, I am creating a bean, but I need to pass it the MyServiceClient object in the constructor, and the catch is that I can't make MyServiceClient a bean because it's from external package and I can't modify it.

@Configuration
public class MyServiceProxyConfiguration {

    @Bean(name = MyServiceProxy.BEAN_NAME)
    public MyServiceProxy getMyServiceProxy(MyServiceClient client) { // could not autowire client
        return new MyServiceProxyImpl(client);
    }
}

So what I would like to do, is being able to pass/autowire an argument to getMyServiceProxy bean. Currently IntelliJ is giving me an error Could not autowire client. How can this be achieved?

UPDATE

Would something like the following work? Because IntelliJ is still reporting an "could not autowire" error. So if I created a bean method that returns the client I want injected, and then add @Inject annotation to the method where I want it injected.

public class MyServiceClientBuilder {

    private final ClientBuilder builder;

    public MyServiceClientBuilder(ClientBuilder builder) {
        this.builder = builder;
    }

    @Bean
    public MyServiceClient build() {
        return builder.newClient();
    }


@Configuration
public class MyServiceProxyConfiguration {

    @Inject
    @Bean(name = MyServiceProxy.BEAN_NAME)
    public MyServiceProxy getMyServiceProxy(MyServiceClient client) { // could not autowire client
        return new MyServiceProxyImpl(client);
    }
}

1条回答
We Are One
2楼-- · 2019-09-15 01:55

You can define MyServiceClient as a separate bean in your configuration file like this:

@Configuration
public class MyServiceProxyConfiguration {

    @Bean
    public MyServiceClient getMyServiceClient () { 
        return MyServiceClient.getInstance(); //initiate MyServiceClient
    }

    @Bean(name = MyServiceProxy.BEAN_NAME)
    public MyServiceProxy getMyServiceProxy(MyServiceClient client) { 
         return new MyServiceProxyImpl(client);
    }
}

I have not tested this code, but it should work.

查看更多
登录 后发表回答