假设我有以下Spring XML声明:
<bean id="myBeanName"
class="org.springframework.remoting.rmi.RmiProxyFactoryBean"
lazy-init="true" p:serviceInterface=
"com.org.MyInterface"
p:serviceUrl="http://myserver:1234/"
p:registryClientSocketFactory-ref="mySocketFactory"
p:refreshStubOnConnectFailure="true" p:lookupStubOnStartup="true"/>
然后我用Spring应用程序Context加载它并调用它。
ApplicationContext factory = new ClassPathXmlApplicationContext("mySpringXML.xml");
MyInterface myInterface = (MyInterface ) factory.getBean("myBeanName");
returnValue = myInterface.invokeMyMethod(arg1, arg2);
现在对比一下,省略Spring XML并直接使用Java Registry进行RMI:
class MySslRMIClientSocketFactory implements RMIClientSocketFactory {
private SSLSocketFactory sf;
public MySslRMIClientSocketFactory(SSLSocketFactory sf) {
this.sf = sf;
}
@Override
public Socket createSocket(String host, int port) throws IOException {
return sf.createSocket(host, port);
}
}
---- inside the calling class
private static SSLContext getSSLContext(KeyStore keyStore) {
// init KeyManagerFactory
KeyManagerFactory keyManagerFactory = null;
TrustManagerFactory trustManagerFactory = null;
SSLContext sslContext = null;
try {
keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password.toCharArray());
trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
// init KeyManager
KeyManager keyManagers[] = keyManagerFactory.getKeyManagers();
TrustManager trustManagers[] = trustManagerFactory
.getTrustManagers();
// init the SSL context
sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return sslContext;
}
public static void main(String[] args) throws KeyStoreException,
NoSuchAlgorithmException, CertificateException, IOException {
KeyStore keystore = getAndLoadKeyStore();
SSLContext sc = getSSLContext(keystore);
SSLSocketFactory sf = sc.getSocketFactory();
try {
RMIClientSocketFactory csf = new MySslRMIClientSocketFactory(sf);
Registry registry = LocateRegistry.getRegistry("myserver", 1234, csf);
MyInterface obj = (MyInterface)registry.lookup("MyInterface");
System.out.println("Found the registry entry");
String message = obj.invokeMyMethod("arg1", 1);
System.out.println(message);
} catch (IOException | NotBoundException e) {
e.printStackTrace();
}
System.out.println("Client done");
}
我的问题是: RmiProxyFactoryBean优于编写自己的包装器(或不使用包装器)有什么好处?
我问这个问题,因为Spring似乎更难调试/分类。 (即使代码行数较少 - 对我而言,它产生的麻烦5到15行之间的差异并不是一个很好的权衡)。
假设