在单个Spring应用程序上下文中具有不同凭据的相同Web服务端口类型?

时间:2014-04-08 14:55:39

标签: java spring web-services

到目前为止,我有一个Web服务客户端,具有固定凭据。现在,我需要相同的应用程序,但只需要不同的凭据。我更喜欢只运行一个应用程序。稍后将根据我的用户状态选择两种可能的Web服务凭证之一,例如ADMINUSER

根据该状态,我希望委托一个或其他凭据。

问题:我正在使用Spring注入创建我的webservice端口,并希望继续这种方法。无论如何,当我现在需要第二个凭证时,我可能必须为webservice客户端创建第二个端口。

但是:我当然不能创建两个相同类型的bean。

@Configuration
public class AppConfig {
    @Bean
    public WsPort getPort() {
        WsPort port = new MyWebService().getWsPort(); //these are auto generated classes from a wsdl
        addCredentials(port, username1, pass1); //sets the HTTP header credentials
        return port;
    }

    //this won't work as WsPort bean must be unique
    @Bean
    public WsPort getPort2() {
        WsPort port = new MyWebService().getWsPort();
        addCredentials(port, username2, pass2);
        return port;
    }
}

我到目前为止使用的是:

@Service
public class MyClient {
    @Autowired
    private WsPort port;

}

当然我不能再像这样使用它,因为我必须根据用户状态选择端口。

我怎么能有两个相同类型的对象(在我的情况下是webservice端口),但是有不同的"内容" (http凭证)?

1 个答案:

答案 0 :(得分:1)

你必须给他们不同的名字:

@Bean(name = "port1")
public WsPort getPort() {
    WsPort port = new MyWebService().getWsPort();
    addCredentials(port, username1, pass1);
    return port;
}

@Bean(name = "port2")
public WsPort getPort2() {
    WsPort port = new MyWebService().getWsPort();
    addCredentials(port, username2, pass2);
    return port;
}

在您的客户端使用限定符:

@Service
public class MyClient {
    @Autowired
    @Qualifier("port1")
    private WsPort port;
}

或者从上下文中获取实例

@Service
public class MyClient {
    @Autowired
    private ApplicationContext context;

    ...

    public void myMethod(){
        context.getBean("port1", WsPort.class).doWhatever();        
    }
}

修改 您也可以只有一个端口作为prototype bean来每次获取一个新实例,并相应地从您的客户端设置登录详细信息

@Bean
@Scope("prototype")
public WsPort getPort() {
    return new MyWebService().getWsPort();
}

@Service
public class MyClient {
    @Autowired
    private WsPort port;

    ...

    public void myMethod(){
        addCredentials(port, username2, pass2);
        ...
    }
}