Injecting dependency to a Spring bean

隐身守侯 提交于 2019-12-25 04:47:10

问题


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:


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.



来源:https://stackoverflow.com/questions/40391028/injecting-dependency-to-a-spring-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!