Spring AOP 發佈和調用無接口的服務

場景 :Spring容器中有不少bean是沒有接口的,如今要把這些bean開發成RMI服務。 java

假設服務端如今有SayHello類: git

package com;

public class SayHello {
	public String say(String name){
		return "Hello,"+name;
	}
}



如今要把這個bean開放成RMI進行遠調用:

1.在服務端增長一個RMIProxy接口: spring

package com;


public interface RMIProxy {
	public Object call(String beanId,String method,Class<?>[] paramsType, Object[] params) throws Exception;
}



2.實現接口:
package com;

import java.lang.reflect.Method;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class RMIProxyImpl implements RMIProxy,ApplicationContextAware{
	private ApplicationContext context;
	@Override
	public Object call(String beanId, String method,Class<?>[] paramsType, Object[] params)throws Exception {
		Object obj = context.getBean(beanId);
		Method mtd = obj.getClass().getDeclaredMethod(method, paramsType);
		return mtd.invoke(obj, params);
	}

	@Override
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
		this.context = arg0;
	}

}



3。配置xml:
bean id="rmiProxy" class="com.RMIProxyImpl"/>
<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
    <property name="serviceName" value="rmiProxy"/>
    <property name="service" ref="rmiProxy"/>
    <property name="serviceInterface" value="com.RMIProxy"/>
    <property name="registryPort" value="1199"/>
</bean>
<bean class="com.SayHello"></bean>



客戶端: express

把SayHello,以及RMIProxy接口拷貝過來; ide

實現一個攔截器: this

package com;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class RMIInterceptor implements MethodInterceptor{
	private RMIProxy rmiProxy;
	@Override
	public Object invoke(MethodInvocation arg0) throws Throwable {
		
		return rmiProxy.call(arg0.getThis().getClass().getName(), arg0.getMethod().getName(),arg0.getMethod().getParameterTypes(), arg0.getArguments());
	}
	public RMIProxy getRmiProxy() {
		return rmiProxy;
	}
	public void setRmiProxy(RMIProxy rmiProxy) {
		this.rmiProxy = rmiProxy;
	}
	

}



配置xml:

<bean id="rmiProxy" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
		<property name="serviceUrl" value="rmi://127.0.0.1:1199/rmiProxy" />
		<property name="serviceInterface" value="com.RMIProxy" />
	</bean>
	<aop:config>

		<aop:pointcut expression="execution(* com.SayHello.*(..))" id="hh" />
		<aop:advisor advice-ref="adri" pointcut-ref="hh" />
	</aop:config>
	<bean id="adri" class="com.RMIInterceptor">
		<property name="rmiProxy" ref="rmiProxy"></property>
	</bean>

	<bean id="sayHello" class="com.SayHello"></bean>



如今再客戶端調用:

SayHello sh = (SayHello) context.getBean("sayHello");
   System.out.println(sh.say("vidy"));



SayHello是從服務端調用過來的。

源碼見這裏 spa

相關文章
相關標籤/搜索